像 @Override 这样的注解在 Java 内部是如何工作的?
谁能向我解释一下注解在 java 内部是如何工作的?
Can anybody explain to me how annotations work internally in java?
我知道如何在 java 中使用 java.lang.annotation 库创建自定义注释.但我仍然不明白它在内部是如何工作的,例如 @Override 注释.
I know how we can create custom annotations by using java.lang.annotation library in java. But I still don't get how it's working internally for example, the @Override annotation.
如果有人能详细解释一下,我将非常感激.
I will be really thankful if anyone could explain that in detail.
推荐答案
注解种类的第一个主要区别是它们是在编译时使用然后被丢弃(如@Override
)还是放置在已编译的类文件中并在运行时可用(如 Spring 的 @Component
).这由 @Retention 决定注释的策略.如果您正在编写自己的注解,则需要确定该注解是在运行时有用(可能用于自动配置)还是仅在编译时有用(用于检查或代码生成).
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).
编译带有注解的代码时,编译器看到注解就像看到源元素上的其他修饰符一样,例如访问修饰符 (public
/private
) 或 最终代码>.当它遇到一个注解时,它会运行一个注解处理器,它就像一个插件类,它表示它对特定的注解感兴趣.注释处理器通常使用反射 API 来检查正在编译的元素,并且可以简单地对它们运行检查、修改它们或生成要编译的新代码.
@Override
是第一个例子;它使用反射 API 来确保它可以在其中一个超类中找到方法签名的匹配项,如果不能,则使用 Messager
导致编译错误.
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.
有许多关于编写注释处理器的教程;这是一个有用的.查看 Processor<上的方法/code> 接口 用于编译器如何调用注解处理器;主要操作发生在
process
方法中,每次编译器看到具有匹配注解的元素时都会调用该方法.
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.
相关文章