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();
}
}
Mein Ziel ist es, die Anmerkung auf wenige Methoden zu überprüfen und, wenn es auf die Anmerkung vorhanden ist, muss ich die Anmerkung bekommen.Laufzeit Anmerkung Scannen, wenn dynamische Laden von Klassen
Demo annotation = m.getAnnotation(Demo.class);
Im obigen Beispiel wird die Annotation in derselben Datei deklariert. Wenn Annotation in einem anderen Paket ist, kann ich so etwas wie
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);
tun, aber wenn ich die DemoClass/AnnotationClass dynamisch wie
Class<?> Demo = Class.forName("com.this.class.DemoClass")
Wie erhalte ich die Anmerkung über die Methoden laden möchten. Ich denke, die unterhalb der Linie tut funktioniert in diesem Fall nicht
Demo annotation = m.getAnnotation(Demo.class);
Können Sie genauer angeben, was Sie erreichen möchten? Versuchen Sie, ein [minimales, vollständiges und überprüfbares Beispiel] (https://stackoverflow.com/help/mcve) zu erstellen. – fragmentedreality
@fragmentedreality aktualisiert die Frage lassen Sie mich wissen, wenn Sie noch Informationen benötigen. – vjr
Ich schlage vor, dass Sie den Titel Ihrer Frage anpassen: Begriff "Annotationsprozessor" hat [spezifische Bedeutung] (https://StackOverflow.com/Tags/annotation-processing/info) im Rahmen der Java-Sprache. Der Begriff, der für Ihre Ziele besser geeignet wäre, ist * Runtime Annotation Scanning * oder einfach [Introspektion] (https://stackoverflow.com/tags/introspection/info). – user1643723