package annotation;
import java.io.Serializable;
import annotation.ValueBind.fieldType;
@SuppressWarnings("serial")
public class Student implements Serializable {
private String name = "";
public String getName() {
return name;
}
@ValueBind(type = fieldType.STRING, value = "aa")
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@ValueBind(type = fieldType.INT, value = "30")
public void setAge(int age) {
this.age = age;
}
public String getStudentId() {
return studentId;
}
@ValueBind(type = fieldType.STRING, value = "101")
public void setStudentId(String studentId) {
this.studentId = studentId;
}
private int age = 0;
private String studentId = "";
}
package annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValueBind {
enum fieldType {
STRING, INT
};
fieldType type();
String value();
}
package annotation;
import java.lang.reflect.Method;
public class PersistStudent {
public static void main(String[] args) throws Exception {
Object c = Class.forName("annotation.Student").newInstance();
try {
Method[] methodArray = c.getClass().getDeclaredMethods();
for (int i = 0; i < methodArray.length; i++) {
if (methodArray[i].isAnnotationPresent(ValueBind.class)) {
ValueBind annotation = methodArray[i].getAnnotation(ValueBind.class);
String type = String.valueOf(annotation.type());
String value = annotation.value();
if (type.equals("INT")) {
methodArray[i].invoke(c, new Integer[] { new Integer(value) });
} else {
methodArray[i].invoke(c, new String[] { value });
}
}
}
Student annotaedStudent = (Student) c;
System.out.println("studentId====" + annotaedStudent.getStudentId() + " studentnName====" + annotaedStudent.getName() + " student Age====" + annotaedStudent.getAge());
} catch (Exception e) {
throw new Exception(e);
}
}
}