import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
// declare a new annotation
@Retention(RetentionPolicy.RUNTIME)
@interface Demo {
String str();
int val();
}
public class PackageDemo {
// set values for the annotation
@Demo(str = "Demo Annotation", val = 100)
// a method to call in the main
public static void example() {
PackageDemo ob = new PackageDemo();
try {
Class c = ob.getClass();
// get the method example
Method m = c.getMethod("example");
// get the annotation for class Demo
Demo annotation = m.getAnnotation(Demo.class);
// print the annotation
System.out.println(annotation.str() + " " + annotation.val());
} catch (NoSuchMethodException exc) {
exc.printStackTrace();
}
}
public static void main(String args[]) {
example();
}
}
私の目的は、いくつかの方法でアノテーションをチェックし、アノテーションにアノテーションが必要な場合、そのアノテーションを取得する必要があります。動的クラスロード時のランタイムアノテーションスキャン
Demo annotation = m.getAnnotation(Demo.class);
上記の例では、アノテーションは同じファイルで宣言されています。注釈が異なるパッケージ内にある場合、私は
import com.this.class.DemoClass
try {
Class c = ob.getClass();
// get the method example
Method m = c.getMethod("example");
// get the annotation for class Demo
Demo annotation = m.getAnnotation(Demo.class);
ような何かを行うことができます。しかし、私は動的に
Class<?> Demo = Class.forName("com.this.class.DemoClass")
ようDemoClass/AnnotationClassをロードしたい場合はどうすればメソッドに注釈を取得します。
Class<?> Demo = Class.forName("com.this.class.DemoClass");
Demo annotation = m.getAnnotation(Demo);
具体的に達成しようとしていることはありますか? [最小で完全で検証可能な例](https://stackoverflow.com/help/mcve)を作成してみてください。 – fragmentedreality
@fragmentedrealityが質問を更新しました。まだ情報が必要な場合は教えてください。 – vjr
私はあなたの質問のタイトルを調整することをお勧めします:用語 "アノテーションプロセッサ"は、[特定の意味](https://stackoverflow.com/tags/annotation-processing/info)をJava言語の範囲に含みます。あなたの目標にもっと適しているという用語は、*ランタイムアノテーションスキャン*または単に[イントロスペクション](https://stackoverflow.com/tags/introspection/info)です。 – user1643723