[英]Retrieving a TYPE_USE annotation declared when creating an Object, using reflection, in Java
使用 Java 8,如果我有這個TYPE_USE注釋:
@Target({ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
我像這樣使用它:
MyObject obj = new @MyAnnotation("test") MyObject();
使用反射,如何在運行時從obj
實例訪問注釋?
如果您打開規范,您會看到您需要使用自定義編譯器插件來處理它們:
因此,如JSR 308 Explained: Java Type Annotations (Oracle) 文章(@see the Processing Type Annotations 章節)中所述,您必須要么編寫自己的插件,要么嘗試使用 Checker Framework。
您可以在此處找到提到的 JSR 269 的(理論上)最新的 Javadoc。
我在這里找到了一個關於如何編寫這個自定義插件的教程,你將需要一個類似的類:
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes({com.example.MyAnnotation.class})
public class MyAnnotationProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
//processing logic here
//returning false means other registered processor can still
//continue processing
return false;
}
}
不幸的是,您將需要創建一個 SPI 文件並且必須打包到 jar 中,因此要使其工作並非易事。
如果已經編寫了適合您需要的插件,那么 Checker 框架的使用可能不那么復雜。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.