如何注解内部工作 [英] How do annotations work internally

查看:175
本文介绍了如何注解内部工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释我如何在Java注解内部工作?

Can anybody explain me how annotation work internally in java?

我知道我们如何可以在Java中使用java.lang.annotation中的库创建自定义的注释。但我仍然没有得到足够的主意它是如何工作的内部像@Override注释。

I know that how we can create custom annotation by using java.lang.annotation library in java. But still i don't get enough idea how it's working internally like @Override annotation.

我真的很感谢,如果有人详细解释。

I really thankful if anyone explain it in details.

推荐答案

种标注之间的第一个主要区别是,他们是否是在编译的时候,然后就丢弃(如 @覆盖),或放置在编译的类文件,并在运行时可用(如Spring的 @Component )。这是通过注释的 @Retention 的策略决定。如果你正在写自己的注释,你需要决定是否标注在运行时有帮助的(对于自动配置,也许)或仅在编译时(检查或code代)。

The first main distinction between kinds of annotation is whether they're used at compile time and then discarded (like @Override) or placed in the compiled class file and available at runtime (like Spring's @Component). This is determined by the @Retention policy of the annotation. If you're writing your own annotation, you'd need to decide whether the annotation is helpful at runtime (for autoconfiguration, perhaps) or only at compile time (for checking or code generation).

在编译code。与注释,编译器看到就像它看到源元素其他修饰,就像访问修饰符(注释公共 / 私人)或最后。当它遇到一个注释,它运行注释处理器,它就像一个插件类,说这是有兴趣的特定注释。注释处理器一般采用反射API检查被编译的元件,并且可以简单地在它们上面运行的检查,对其进行修改,或产生新的code进行编译。 @覆盖是第一个例子;它使用反射API,以确保它可以在某个超找到方法签名匹配,并使用梅萨引起编译错误,如果它不能。

When compiling code with annotations, the compiler sees the annotation just like it sees other modifiers on source elements, like access modifiers (public/private) or final. When it encounters an annotation, it runs an annotation processor, which is like a plug-in class that says it's interested a specific annotation. The annotation processor generally uses the Reflection API to inspect the elements being compiled and may simply run checks on them, modify them, or generate new code to be compiled. @Override is an example of the first; it uses the Reflection API to make sure it can find a match for the method signature in one of the superclasses and uses the Messager to cause a compile error if it can't.

有一些写作上的注解处理器提供的教程;这里是一个有用的。看通过处理器编译器是如何调用注释处理器接口;主要操作发生在过程方法,该方法被调用每一个编译器看到有一个匹配注释元素的时间。

There are a number of tutorials available on writing annotation processors; here's a useful one. Look through the methods on the Processor interface for how the compiler invokes an annotation processor; the main operation takes place in the process method, which gets called every time the compiler sees an element that has a matching annotation.

这篇关于如何注解内部工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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