标签:string 表示 value equal retention type document src round
//注解中的成员变量非常像定义接口
public @interface MyAnnotation {
//不带有默认值
String name();
//带有默认值
int age() default 20;
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValueBind {
filedType type();
String value() default "SUSU";
enum filedType {
STRING, INT
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValueBind {
filedType type();
String value() default "SUSU";
enum filedType {
STRING, INT
}
}
public class Person implements Serializable {
private String name;
private int age;
public String getName() {
return name;
}
@ValueBind(type = ValueBind.filedType.STRING, value = "LCF")
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@ValueBind(type = ValueBind.filedType.INT, value = "21")
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
‘}‘;
}
}
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
Object person = Class.forName("Person").newInstance();
//以下获取的是:类的注解
// Annotation[] annotations = person.getClass().getAnnotations();
Method[] methods = person.getClass().getMethods();
for (Method method : methods) {
//如果该方法上面具有ValueBind这个注解
if (method.isAnnotationPresent(ValueBind.class)) {
//通过这个注解可以获取到注解中定义的
ValueBind annotation = method.getAnnotation(ValueBind.class);
if (annotation.type().equals(ValueBind.filedType.STRING)) {
method.invoke(person, annotation.value());
} else {
method.invoke(person, Integer.parseInt(annotation.value()));
}
}
}
System.out.println(person);
}
}
标签:string 表示 value equal retention type document src round
原文地址:http://www.cnblogs.com/LiuChunfu/p/6675920.html