jeudi 10 mai 2018

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);
}

Now that I've mentioned the context.

I want to make sure that all methods that are annotated with @Initialize do not have any parameter.





Aucun commentaire:

Enregistrer un commentaire