Use cases for java annotation and more

2019-08-04 16:11发布

问题:

as far as i know, the only way to make the annotation take effect is reflection. Without reflection, java annotation become useless. Is this right?

public class Main{
    @SomeAnnotation(name="some",value="annotation")
    public void method(){
        //do something.
    }
    public static void main(String...args){
        Main main = new Main();
        //Just call the method directly, How to make the @SomeAnnotation make sense?
        main.method();
    }
}

For instance, you first get a java Method object, then check all the annotations presented. And if you get what you want, then invoke the method by reflection. eg.

Method.invoke(Object, Object...args) 

People say annotation can reduce the tedious XML, but back to the XML configuration, the use pattern likes we load and parse the XML file, when we call some method ,we first get or check configuration info, then do the real stuff. How to achieve this by Annotation? The only way we got is reflection?

回答1:

The RetentionPolicy of annotations (which itself is declared as a meta-annotation) shows you that annotations are not only used by reflection, but also at compile or build time (like with the annotation processing tool).

If you need sample code for understanding annotation processing, it is available at the end of the annotation documentation (by means of a small program inspecting another test class).