Java注释的用例及更多 [英] Use cases for java annotation and more

查看:67
本文介绍了Java注释的用例及更多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,使注释生效的唯一方法是反射。没有反射,Java注释将变得无用。

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

例如,您首先获得一个Java 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) 

人们说注解可以减少乏味的XML,但是回到XML配置,使用模式就像我们在调用某种方法时加载并解析XML文件一样,我们首先获取或检查配置信息,然后进行实际操作。如何通过注释实现这一目标?

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?

推荐答案

RetentionPolicy 向您显示注释不仅用于反射,而且还用于编译或构建时间(例如使用注释处理工具 )。

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

这篇关于Java注释的用例及更多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆