問(wèn)題描述
誰(shuí)能向我解釋一下注解在 java 內(nèi)部是如何工作的?
Can anybody explain to me how annotations work internally in java?
我知道如何在 java 中使用 java.lang.annotation 庫(kù)創(chuàng)建自定義注釋.但我仍然不明白它在內(nèi)部是如何工作的,例如 @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.
如果有人能詳細(xì)解釋一下,我將非常感激.
I will be really thankful if anyone could explain that in detail.
推薦答案
注解種類(lèi)的第一個(gè)主要區(qū)別是它們是在編譯時(shí)使用然后被丟棄(如@Override
)還是放置在已編譯的類(lèi)文件中并在運(yùn)行時(shí)可用(如 Spring 的 @Component
).這由 @Retention 決定注釋的策略.如果您正在編寫(xiě)自己的注解,則需要確定該注解是在運(yùn)行時(shí)有用(可能用于自動(dòng)配置)還是僅在編譯時(shí)有用(用于檢查或代碼生成).
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).
編譯帶有注解的代碼時(shí),編譯器看到注解就像看到源元素上的其他修飾符一樣,例如訪(fǎng)問(wèn)修飾符 (public
/private
) 或 最終代碼>.當(dāng)它遇到一個(gè)注解時(shí),它會(huì)運(yùn)行一個(gè)注解處理器,它就像一個(gè)插件類(lèi),它表示它對(duì)特定的注解感興趣.注釋處理器通常使用反射 API 來(lái)檢查正在編譯的元素,并且可以簡(jiǎn)單地對(duì)它們運(yùn)行檢查、修改它們或生成要編譯的新代碼.
@Override
是第一個(gè)例子;它使用反射 API 來(lái)確保它可以在其中一個(gè)超類(lèi)中找到方法簽名的匹配項(xiàng),如果不能,則使用 Messager
導(dǎo)致編譯錯(cuò)誤.
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.
有許多關(guān)于編寫(xiě)注釋處理器的教程;這是一個(gè)有用的.查看 Processor<上的方法/code> 接口 用于編譯器如何調(diào)用注解處理器;主要操作發(fā)生在
process
方法中,每次編譯器看到具有匹配注解的元素時(shí)都會(huì)調(diào)用該方法.
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.
這篇關(guān)于像 @Override 這樣的注解在 Java 內(nèi)部是如何工作的?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!