MyValueBind.java
package com.yy.method;
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 MyValueBind {
enum fieldType{
String,INT
};
fieldType type();
String value();
}
Student.java
package com.yy.method;
import com.yy.method.MyValueBind.fieldType;
public class Student {
private String name;
private int age;
private String id;
public String getName() {
return name;
}
@MyValueBind(type=fieldType.String,value="牵手无奈")
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@MyValueBind(type=fieldType.INT,value="23")
public void setAge(int age) {
this.age = age;
}
public String getId() {
return id;
}
@MyValueBind(type=fieldType.String,value="1516651")
public void setId(String id) {
this.id = id;
}
}
package com.yy.method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class PersistStudent {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
try {
persistAStudent();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void persistAStudent() throws ClassNotFoundException, NumberFormatException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException{
Object o = Class.forName("com.yy.method.Student").newInstance();
Method[] methods = o.getClass().getDeclaredMethods();
for(Method method:methods){
if(method.isAnnotationPresent(MyValueBind.class)){
MyValueBind valueBind = method.getAnnotation(MyValueBind.class);
String type = String.valueOf(valueBind.type());
String value = String.valueOf(valueBind.value());
if(type.equals("INT")){
method.invoke(o, new Integer[]{new Integer(value)});
}else{
method.invoke(o, new String[]{value});
}
}
}
Student student = (Student)o;
System.out.println("name="+student.getName()+" age="+student.getAge()+" id="+student.getId());
}
}