import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.annotation.Resource;
public class TestAnnotation {
public static void main(String[] args) throws Exception {
F f = new F();
Class clazz = f.getClass();
Field field = clazz.getDeclaredField("mm");
field.setAccessible(true);//把私有成员变成可以访问
Resource resource = field.getAnnotation(Resource.class);
Class c = field.getType();//获取成员的类型MM
Method setMethod = clazz.getDeclaredMethod("setMm", MM.class);//获取带参数指定的方法
setMethod.invoke(f, c.newInstance());// f.setMm(new MM());
System.out.println(f.getMm().getName());
}
}
class F {
// @Bar(name = "123", c=F.class, type=Types.ONE, v=100)
// public void tt() {
// System.out.println("-------------");
// }
@Resource
private MM mm;
public MM getMm() {
return mm;
}
public void setMm(MM mm) {
this.mm = mm;
}
}
class MM {
private String name = "55555";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
enum Types {
ONE, TWO
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Bar {
String name();
String val() default "456";
Class c();
int v();
Types type();
}