Eth*_*rio 5 java reflection annotations
问题:是否有办法对方法进行代码检查并检查它是否没有参数并在编译前警告我,或者甚至在我的IDE中给出警告.
假设我有一个注释 @Initialize
@Retention(RetentionPolicy.RUNTIME)
public @interface Initialize {
int priority();
}
Run Code Online (Sandbox Code Playgroud)
通过反射,我可以调用带注释的方法 @Initialize
public static void initMethods(Initializable clazz) {
TreeMap<Integer, Method> methods = prioritizedMethods(clazz.getClass().getDeclaredMethods());
methods.forEach((priority, method) -> {
try {
method.setAccessible(true);
Logger.debug("Invoking " + method.getName() + "...");
method.invoke(clazz);
} catch (IllegalAccessException | InvocationTargetException e) {
Logger.debug("Failed to invoke " + method.getName());
e.printStackTrace();
}
});
}
Run Code Online (Sandbox Code Playgroud)
prioritzedMethods(Method[] method) 是我检查注释的地方.
private static TreeMap<Integer, Method> prioritizedMethods(Method[] methods) {
HashMap<Integer, Method> taggedMethods = new HashMap<>();
for (Method method : methods) {
if (method.isAnnotationPresent(Initialize.class)) {
Initialize meta = method.getAnnotation(Initialize.class);
taggedMethods.put(meta.priority(), method);
}
}
return new TreeMap<>(taggedMethods);
}
Run Code Online (Sandbox Code Playgroud)
我想确保所有注释的方法都@Initialize没有任何参数.
我已经为这种常见需求编写了一个框架。看deannotation-checker。
您唯一应该做的就是添加@CheckMethod注释。
@CheckMethod(argCount = 0, returnType = @CheckType(void.class))
public @interface Init {
...
}
Run Code Online (Sandbox Code Playgroud)
现在您的注释可以限制注释的方法。如果你像这样使用它
@Init
public void func(int i) {
...
}
Run Code Online (Sandbox Code Playgroud)
你会得到编译错误
[5,15] Must only have 0 arguments.
Run Code Online (Sandbox Code Playgroud)
如果你的IDE支持(我使用的是eclipse和m2e-apt插件),你可以在保存文件时得到错误。