Reputation: 53
The question: Is there a way to do code inspection for a method and check if it doesn't have a parameter and warn me before compilation, or even give me a warning in my IDE.
Let's say I have an annotation @Initialize
@Retention(RetentionPolicy.RUNTIME)
public @interface Initialize {
int priority();
}
And with reflect, I can invoke methods that are annotated with @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();
}
});
}
prioritzedMethods(Method[] method)
is where I check for annotation.
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);
}
I want to make sure that all methods that are annotated with @Initialize
do not have any parameter.
Upvotes: 5
Views: 135
Reputation: 4691
I have written a framework for such common requirement. See deannotation-checker
.
The only thing you should do is add @CheckMethod
on your annotation.
@CheckMethod(argCount = 0, returnType = @CheckType(void.class))
public @interface Init {
...
}
Now your annotation has ability to restrict the annotated method. If you use it like
@Init
public void func(int i) {
...
}
You will get compile error
[5,15] Must only have 0 arguments.
If you IDE support (I'm using eclipse and m2e-apt plugin), you can get the error when save the file.
Upvotes: 2