使用注解的类
public class Student implements Serializable { private String name = ""; public String getName() { return name; } @ValueBind(type = ValueBind.fieldType.STRING, value ="aa") public void setName(String name) { this.name = name; } public int getAge() { return age; } @ValueBind(type = ValueBind.fieldType.INT, value ="30") public void setAge(int age) { this.age = age; } public String getStudentId() { return studentId; } @ValueBind(type = ValueBind.fieldType.STRING, value ="101") public void setStudentId(String studentId) { this.studentId = studentId; } private int age = 0; private String studentId = ""; }
注解类:
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ValueBind { enum fieldType{ STRING, INT }; fieldType type(); String value(); }
测试类:
public class PersistStudent { public static void main(String[] args) throws Exception { Object c = Class.forName("com.mogujie.service.tagcenter.query.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); } } }