//注解中的成员变量非常像定义接口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)@Documentedpublic @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;}@Overridepublic 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);}}
原文:http://www.cnblogs.com/LiuChunfu/p/6675920.html