package com.itheima.Test;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
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 Test {
public static void main(String[] args) throws Exception {
}
public static void get() throws Exception{
Person p = new Person();
String propertyName = "Name";
String propertyAge = "Age";
Object valueName = "san";
Object value = 20;
/*Java7的新特性
Map map = (name:"zxx",age:18);
BeanUtils.setProperty(map, "name", "lhm");*/
//把返回来的值进行自动转换(String)
BeanUtils.setProperty(p, "name","name");
//System.out.println(BeanUtils.getProperty(p, "name").getClass().getName());
BeanUtils.setProperty(p, "birthday.time", "2013118");
//System.out.println(BeanUtils.getProperty(p, "birthday.time"));
//返回原类型的值 不进行转换(字符串)
PropertyUtils.setProperty(p, "age", 20);
Object obj = PropertyUtils.getProperty(p, "age").getClass();
System.out.println(obj);
}
public static void run() throws Exception {
Person p = new Person("sun", 20);
getMethod(p);
}
public static void getMethod(Object p) throws Exception {
String propertyName = "Name";
String propertyAge = "Age";
Object valueName = "san";
Object value = 20;
setPropertyName(p, propertyName, valueName);
getPropertyName(p, propertyName);
setPropertyAge(p, propertyAge, value);
getProperAge(p, propertyAge);
}
public static void getProperAge(Object obj, String propertyAge)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd1 = new PropertyDescriptor(propertyAge,
obj.getClass());
Method methodGetAge = pd1.getReadMethod();
Object o = methodGetAge.invoke(obj);
System.out.println(o);
}
public static void setPropertyAge(Object obj, String propertyAge,
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor pd1 = new PropertyDescriptor(propertyAge,
obj.getClass());
Method methodSetAge = pd1.getWriteMethod();
methodSetAge.invoke(obj, value);
Person p = (Person) obj;
System.out.println(p.getAge());
}
private static void setPropertyName(Object obj, String propertyName,
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,
obj.getClass());
Method methodSetName = pd2.getWriteMethod();
methodSetName.invoke(obj, value);
Person p = (Person) obj;
System.out.println(p.getName());
}
private static void getPropertyName(Object obj, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd1 = new PropertyDescriptor(propertyName,
obj.getClass());
Method methodGetName = pd1.getReadMethod();
Object o = methodGetName.invoke(obj);
System.out.println(o);
}
}
{:soso_e129:}全部已经学会调用
|
|