先声明两个注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface MyFieldAnnotation {
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface MyMethodAnnotation {
String value();
String other();
}
再声明一个类 A
public class A {
@MyFieldAnnotation
private String name ="张三";
public String sex ="男";
public A() {
}
public A(String name, String sex) {
this.name = name;
this.sex = sex;
}
@MyMethodAnnotation(value = "注解的值",other = "另一个值")
public String methodA(String msg){
return msg;
}
private int methodB(int i){
return i;
}
}
开始反射 A 对象
A a = new A();
Class clazz = a.getClass();
Package clazzPackage = clazz.getPackage();
String clazzName = clazz.getName();
Field[] publicFields = clazz.getFields();
Field[] allFields = clazz.getDeclaredFields();
Field sex = clazz.getField("sex");
Field name = clazz.getDeclaredField("name");
name.setAccessible(true);
A newA = (A)clazz.newInstance();
name.set(newA,"李四");
Method[] methods = clazz.getMethods();
Method[] declaredMethods = clazz.getDeclaredMethods();
Method methodA = clazz.getMethod("methodA", String.class);
A newA2 = (A)clazz.newInstance();
Object result = methodA.invoke(newA2,"执行方法");
System.out.println(result);
Method methodB = clazz.getDeclaredMethod("methodB",int.class);
Annotation[] fieldAnnotations = name.getAnnotations();
Annotation myFieldAnnotation = name.getAnnotation(MyFieldAnnotation.class);
Annotation[] methodBAnnotations = methodA.getAnnotations();
MyMethodAnnotation myMethodAnnotation = methodA.getAnnotation(MyMethodAnnotation.class);
String value = myMethodAnnotation.value();
System.out.println(value);
String other = myMethodAnnotation.other();
System.out.println(other);