Sanjay Verma
Sanjay Verma

Reputation: 1626

Java code - how to remove only annotated methods with script

I wonder if there is a way (a gradle script or any script or any other way without an IDE) to remove methods annotated with certain annotations. Example:

class x {
  public static void main(String[] args) {
    int x = getValue();
    System.out.println(x);
  }

  @RemoveEnabled(id = "getValueMethod1", return = "10")
  int getValue() {
    return 20;
  }
}

Now when I run the script or gradle target, it should remove the getValue() method, and the output code should become:

class x {
  public static void main(String[] args) {
    int x = 10;
    System.out.println(x);
  }
}

Is there an existing script or way to achieve this? It might be achievable with grep and String parsing etc., but I'm looking for a cleaner solution which is able to get all methods by an annotation id, and remove them with formatting. I tried searching on Google, Stack Overflow etc., but couldn't find a solution.

Upvotes: 0

Views: 613

Answers (1)

KnIfER
KnIfER

Reputation: 750

I wrote a module to process similiar task.

https://github.com/KnIfER/Metaline

@StripMethods(keys={"ToRemove","AlsoRemove"})
public class YourCLZ{

void ToRemove(){} // will be removed

void AlsoRemove(){} // will be removed

@StripMethods(strip=true)
void AnotherTest(){} // will also be removed

}

in your case

@StripMethods(keys="getValue")
class yourx {
  public static void main(String[] args) {
    int x = getValue();
    System.out.println(x);
  }

  int getValue() {
    return 20;
  }
}

will become:

class yourx {
  public static void main(String[] args) {
    System.out.println(x);
  }
}

you will get a compilation error since for now my module simply remove any methods or method body statements that contain the key you specified.

Upvotes: 1

Related Questions