Use cases for java annotation and more

怎甘沉沦 提交于 2019-12-24 06:49:30

问题


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).



来源:https://stackoverflow.com/questions/11515833/use-cases-for-java-annotation-and-more

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!