您可以使用 Java 中的某些东西来批量修改您的 Java 项目。诀窍是使用自定义注释处理器。使用注释处理器,您几乎可以修改所有内容。
例如,this library ( for ecilipse and IDEA ) 将一些 String 字段成员修改为 /**multiline*/ 文档。
研究库让我也有能力修改方法体。
今天,我想去掉android支持库中一些不需要的方法(用作可编辑的本地模块)。我可以手动删除它们,但之后很难保持更新。
因此,我决定编写另一个注释处理器,允许您删除一些类成员,而不是使用脚本或手动修改代码。
对于IDEA来说,概念验证代码非常简单:
// 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;
}
}
成员删除导致的结果错误:
Test.java:10: error: cannot find symbol
int variableToRemove = FieldToRemove;
^
symbol: variable FieldToRemove
location: class Test
还有很长的路要走。完成后我会发布代码。
完成。见https://github.com/KnIfER/Metaline
示例用法,从 androidx/appcompat 中移除 NightMode:
@StripMethods(key="Night")
public class AppCompatActivity
...
@StripMethods(key="Night")
public abstract class AppCompatDelegate
...
@StripMethods(key="Night")
class AppCompatDelegateImpl
...