java注释的用例等等 [英] Use cases for java annotation and more

查看:23
本文介绍了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文件,当我们调用某个方法时,我们首先获取或检查配置信息,然后做真正的事情.如何通过 Annotation 实现这一点?我们得到的唯一方法是反射?

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天全站免登陆