外部调用getProperty方法时只须要传入实体对象便可;例如TestUtil.getProperty(new User());java
外部调用setProperty方法时只须要传入实体对象和要set的值便可;例如TestUtil.setProperty(new User(), "setValue");工具
这里调用setProperty方法后User类中全部字段的值都将变为"setValue",因此这里想要给不一样的字段set不一样的值,则换一个参数spa
如下是核心工具类,code
package com.qcp.test;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
public class TestUtil {
/* 该方法用于传入某实例对象以及对象方法名,经过反射调用该对象的某个get方法 */
public static void getProperty(Object beanObj){
try {
Field[] fields = beanObj.getClass().getDeclaredFields();//得到属性
Class clazz = beanObj.getClass();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
// 此处应该判断beanObj,property不为null
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
if (getMethod != null) {
System.out.println(beanObj+"的字段是:"+field.getName()+",类型是:"+field.getType()+",取到的值是: "+getMethod.invoke(beanObj));
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IntrospectionException e) {
e.printStackTrace();
}
}
/* 该方法用于传入某实例对象以及对象方法名、修改值,经过放射调用该对象的某个set方法设置修改值 */
public static void setProperty(Object beanObj,
Object value){
try {
Field[] fields = beanObj.getClass().getDeclaredFields();//得到属性
Class clazz = beanObj.getClass();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
// 此处应该判断beanObj,property不为null
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), beanObj.getClass());
Method setMethod = pd.getWriteMethod();
if (setMethod != null) {
System.out.println(beanObj+"的字段是:"+field.getName()+",参数类型是:"+field.getType()+",set的值是: "+value);
//这里注意实体类中set方法中的参数类型,若是不是String类型则进行相对应的转换
setMethod.invoke(beanObj, value);//invoke是执行set方法
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IntrospectionException e) {
e.printStackTrace();
}
}
}