最近接触了一个新的get和set方法,好处就是可以把Java bean的所有property都定义在一个String list里,利用循环语句一次性进行get或者set,可以简化很多代码。
相关API:
PropertyDescriptor
Method
代码干货:
这是一个测试用的Java bean。
package string.prodes;
public class TestBean {
private String pro;
private int index;
public TestBean(){
}
public String getPro() {
return pro;
}
public void setPro(String pro) {
this.pro = pro;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
这是工具类,核心
package string.prodes;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestUtil {
/*该方法用于传入某实例对象以及对象方法名,通过反射调用该对象的某个get方法*/
public static Object getProperty(Object beanObj, String property) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
//此处应该判断beanObj,property不为null
PropertyDescriptor pd = new PropertyDescriptor(property, beanObj.getClass());
Method getMethod = pd.getReadMethod();
if(getMethod == null){
}
return getMethod.invoke(beanObj);
}
/*该方法用于传入某实例对象以及对象方法名、修改值,通过放射调用该对象的某个set方法设置修改值*/
public static Object setProperty(Object beanObj, String property, Object value) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
//此处应该判断beanObj,property不为null
PropertyDescriptor pd = new PropertyDescriptor(property, beanObj.getClass());
Method setMethod = pd.getWriteMethod();
if(setMethod == null){
}
return setMethod.invoke(beanObj, value);
}
}
测试main
package string.prodes;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
public class TestPropertyDescriptor {
public static void main(String[] args) {
TestBean bean = new TestBean();
bean.setPro("1");//Set the value to test getMethod.
bean.setIndex(1);
Object proValue;
Object indexValue;
try {
//Get pro value from bean.
proValue = TestUtil.getProperty(bean, "pro");
indexValue = TestUtil.getProperty(bean, "index");
System.out.println("Get pro: " + proValue.toString());
System.out.println("Get index: " + indexValue.toString());
Integer idx = (Integer)indexValue;
System.out.println("Whether get success: " + (idx.intValue() == bean.getIndex()));
//Set value to pro of bean.
TestUtil.setProperty(bean, "pro", "2");
TestUtil.setProperty(bean, "index", 2);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println("Set pro: " + bean.getPro());
System.out.println("Set index: " + bean.getIndex());
}
}
运行结果:
Get pro: 1
Get index: 1
Whether get success: true
Set pro: 2
Set index: 2
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/scau_syd/article/details/46907573