zookastos
zookastos

Reputation: 945

Java - Not able to get value of Custom Annotation

I have a custom Annotation like this -

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ControllerAction {
    String value();
}

I have a class that uses this annotation like this -

public class TestController extends AbstractController {

    public TestController () {
        super();
    }

    @ControllerAction("add")
    public void addCandidate(){

    }

}

The super class looks like this -

public abstract class AbstractController {

    public AbstractController (){

    }

    public CustomBean processRequest(ServletAction action, HttpServletRequest request) {
        Class<AbstractController > controllerClass = AbstractController.class;
        for (Method method : controllerClass.getDeclaredMethods()) {
            if (method.isAnnotationPresent(ControllerAction.class)) {
                Annotation annotation = (ControllerAction) method.getAnnotation(ControllerAction.class);
                if(annotation != null){
                    if(annotation.value().equals(action.getAction())){
                        method.invoke(controllerClass.newInstance());
                    }
                }
            }
        }
        return null;
    }
}

The processRequest(...) method in AbstractController is called from a servlet directly. The processRequest() method figures out the servlet action, and based on that, it should call the method appropriately. For example, if the ServletAction.getAction() == 'add', processRequest() should automatically call addCandidate() in TestController. But I am not able to get the value of the Annotation. Somehow annotation.value() is giving a compilation error in eclipse. Eclipse is not showing any method I can use to get the annotation value.

I want to know if there is a way to get value() of the Custom Annotation. I dont want to define my Annotation with anything else other than String value(). I want to know if it is possible to achieve what I want with just String value() in my custom Annotation?

Any help is greatly appreciated. Thanks.

Upvotes: 0

Views: 616

Answers (1)

dpr
dpr

Reputation: 10972

You probably need to change

Annotation annotation = (ControllerAction) method.getAnnotation(ControllerAction.class);

To

ControllerAction annotation = method.getAnnotation(ControllerAction.class);

Otherwise the methods specific to ControllerAction will not be known to the compiler as annotation is of type Annotation

Additionally - as pointed out by Sharon Ben Asher - instead of AbstractController.class you should use getClass() to get the class of the actual implementation at runtime. Given the current code only the methods of AbstractController will be checked but not the ones of implementing classes.

Upvotes: 3

Related Questions