import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(value=RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String name();
}
public class AnnonTestA {
public void methodA(){
}
@MyAnnotation(name="111")
public void methodA(String a) throws Exception{
AnnonTestB.methodB("methodA",String.class);
}
}import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class AnnonTestB {
public static void methodB(String methodName, Class<?>... parameterTypes) throws Exception {
AnnonTestA annonTestA = new AnnonTestA();
// 获取AnnotationTest2的Class实例
Class<AnnonTestA> c = AnnonTestA.class;
// 获取需要处理的方法Method实例
Method method = c.getMethod(methodName, parameterTypes);
Method[] methods = c.getMethods();
// 判断该方法是否包含MyAnnotation注解
if (method.isAnnotationPresent(MyAnnotation.class)) {
// 获取该方法的MyAnnotation注解实例
MyAnnotation myAnnotation = method
.getAnnotation(MyAnnotation.class);
// 执行该方法
// method.invoke(annonTestA, "12345");
// 获取myAnnotation
String value1 = myAnnotation.name();
System.out.println(value1);
}
// 获取方法上的所有注解
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
}
}import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class TestString {
public static void main(String[] args) throws Exception {
AnnonTestA annonTestA = new AnnonTestA();
annonTestA.methodA("123");
}
}
代码都给上了,不明白再追问吧。
参考地址:http://blog.csdn.net/bao19901210/article/details/17201173
追问![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/359b033b5bb5c9eadc45be77d339b6003bf3b3f4?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)