黑马程序员 java高级技术1.5之内省和BeanUtils(1.7)(张孝祥)(二)
2014-11-24 03:26:40
·
作者:
·
浏览: 1
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
public class IntroSpectorTest {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ReflectPoint pt1 = new ReflectPoint(3,5);
String propertyName = "x";
//"x"-->"X"-->"getX"-->MethodGetX-->
Object retVal = getProperty(pt1, propertyName);
System.out.println(retVal);
Object value = 7;
setProperties(pt1, propertyName, value);
System.out.println(BeanUtils.getProperty(pt1, "x").getClass().getName());
BeanUtils.setProperty(pt1, "x", "9");
System.out.println(pt1.getX());
/*BeanUtils中Map和javabean可以相互转换,
*BeanUtils是第三方开发的,直接拿来用,以后工作会用
//java7的新特性
Map map = {name:"zxx",age:18};
BeanUtils.setProperty(map, "name", "lhm");
*/
//BeanUtils可以对基本类型进行转换,表单填写进来的是字符串,回应给浏览器的可以是int
BeanUtils.setProperty(pt1, "birthday.time", "111");
System.out.println(BeanUtils.getProperty(pt1, "birthday.time"));//BeanUtils的好处,联合属性的应用
PropertyUtils.setProperty(pt1, "x", 9);//不能写字符串的9,是什么类型就是什么类型,不会进行类型转换
System.out.println(PropertyUtils.getProperty(pt1, "x").getClass().getName());
}
private static void setProperties(Object pt1, String propertyName,
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,pt1.getClass());//内省操作属性
Method methodSetX = pd2.getWriteMethod();//写属性方法,set
methodSetX.invoke(pt1,value);//调用反射的执行方法
}
private static Object getProperty(Object pt1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
/*通过内省操作javabean的属性,更简单
* PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodGetX = pd.getReadMethod();读属性方式
Object retVal = methodGetX.invoke(pt1);*/
BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());//第二种方式的内省,内省操作属性
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
Object retVal = null;
for(PropertyDescriptor pd : pds){
if(pd.getName().equals(propertyName))
{
Method methodGetX = pd.getReadMethod();//get
retVal = methodGetX.invoke(pt1);//调用反射的执行方法
break;
}
}
return retVal;
}
}
运行结果:
3
java.lang.String
9
111
java.lang.Integer