You can use something in Java to batch-modify your Java project. The trick is to use a custom annotation processor. With annotation processor you can modify almost everything.
For an example, this library ( for ecilipse and IDEA ) modifies some String field members to it's /**multiline*/
docs.
Studying the library gives me the power to modify the method body as well.
Today, I want to strip out some unwanted methods in the android support library( used as editable local module ). I can manually remove them, but it would be hard to keep udpate after that.
So, instead of using script or mere-hand to modify the code directly, I decide to write another annotation processor which allow you to remove some class members.
For IDEA, the concept-proving code is very simple:
// the custom annotation
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
public @interface StripMethods {
boolean strip() default true;
String key() default "";
}
// processing the custom annotation
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
Set<? extends Element> fields = roundEnv.getElementsAnnotatedWith(StripMethods.class);
for (Element field : fields) {
StripMethods annotation = field.getAnnotation(StripMethods.class);
ElementKind KIND = field.getKind();
if(KIND == ElementKind.CLASS) {
// the class declaration
JCTree.JCClassDecl laDcl = (JCTree.JCClassDecl) elementUtils.getTree(field);
// the definition tree list
ArrayList<JCTree> defs = new ArrayList<>(laDcl.defs);
// remove the second member which in this case is a string field
defs.remove(2);
// finally modify the class definition
laDcl.defs = List.from(defs);
}
}
}
@StripMethods
public class Test {
// the first member is the default constructor
static {
}
static final int FieldToRemove = 0;
@Test
public void test() {
int variableToRemove = FieldToRemove;
}
}
the result error caused by the member removal:
Test.java:10: error: cannot find symbol
int variableToRemove = FieldToRemove;
^
symbol: variable FieldToRemove
location: class Test
Still a long way to go. I will publish the code when it's finished.
Done. see https://github.com/KnIfER/Metaline
Exmaple usage, removing NightMode from androidx/appcompat:
@StripMethods(key="Night")
public class AppCompatActivity
...
@StripMethods(key="Night")
public abstract class AppCompatDelegate
...
@StripMethods(key="Night")
class AppCompatDelegateImpl
...