Ethan Bacurio
Ethan Bacurio

Reputation: 53

Check if method requires a parameter using annotation and reflect

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

Answers (2)

Dean Xu
Dean Xu

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.

enter image description here

Upvotes: 2

k_ssb
k_ssb

Reputation: 6252

method.getParameterTypes().length == 0 if and only if method has no parameters. (Javadoc)

Upvotes: 2

Related Questions