public class reflectTest {
/**
* 利用反射设置实体类的属性
*
* @return
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static boolean setAttributes(Class<?> classPath)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException,
NoSuchFieldException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
Class cls;
cls = Class.forName(Student.class.getName());
Object tObject = cls.newInstance();
Field field = cls.getDeclaredField("id");
field.setAccessible(true); // 设置私有属性范围
field.set(tObject, 10);
System.out.print("field得到的值" + field.get(tObject) + "\n");
Method method = cls.getMethod("setId", int.class);
method.invoke(tObject, 11);
Method getMethod = cls.getMethod("getId");
System.out.println("method得到的值" + getMethod.invoke(tObject));
return true;
}
/**
* 利用反射获取实体类的属性
*
* @return
* @throws IntrospectionException
* @throws ClassNotFoundException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static boolean getAttributes(Class<?> classPath, Object obj) throws IntrospectionException,
ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
PropertyDescriptor[] pds;
pds = Introspector.getBeanInfo(classPath).getPropertyDescriptors();
Class cls = Class.forName(classPath.getName());
Field[] fieldlist = cls.getDeclaredFields();
for (PropertyDescriptor pd : pds) {
for (int i = 0; i < fieldlist.length; i++) {
if (fieldlist[i].getName().equals(pd.getName())) {
Method getter = pd.getReadMethod();
Object value = getter.invoke(obj);
System.out.println(fieldlist[i].getName() + "==="
+ value);
}
}
}
return true;
}
public static void main(String[] args) throws IllegalArgumentException, IntrospectionException,
ClassNotFoundException, IllegalAccessException, InvocationTargetException, SecurityException,
InstantiationException, NoSuchFieldException, NoSuchMethodException {
Student student = new Student();
student.setAddress("china");
student.setEmail("zt123qq.com");
student.setId(1);
student.setName("zt");
Birthday day = new Birthday("2010-11-22");
student.setBirthday(day);
System.out.println(getAttributes(Student.class, student));
System.out.println(setAttributes(Student.class));
}
}