問題描述
誰能向我解釋一下注解在 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.
這篇關于像 @Override 這樣的注解在 Java 內部是如何工作的?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!