黑马程序员技术交流社区
标题:
内省,哪里出了错了呢?
[打印本页]
作者:
坚持525
时间:
2014-11-5 20:33
标题:
内省,哪里出了错了呢?
本帖最后由 坚持525 于 2014-11-5 20:50 编辑
程序编译时可以的,运行出现了这个,怎么回事?
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.commons.beanutils.BeanUtils;
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class BeansTest {
public static void main(String[] args) throws Exception {
Person p = new Person();
p.setName("王赫");
String propertiesName = "name";
String name = extracted(p, propertiesName);// 演示了用eclipse抽取方法
System.out.println(name);
String propertiesAge = "age";
int age = 23;
SetAge(p, propertiesAge, age);
String name1 = BeanUtils.getProperty(p, "name");
// 使用beanUtils工具包进行获取和设置属性(尽管这些属性是私有的,可是有方法啊,是不是很方便)
System.out.println(BeanUtils.getProperty(p, "name").getClass()
.getName());
System.out.println(name1);
BeanUtils.setProperty(p, "age", 19);
System.out.println(p.getAge());
}
private static void SetAge(Person p, String propertiesAge, int age)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor bp1 = new PropertyDescriptor(propertiesAge,
p.getClass());
Method methodSetAge = bp1.getWriteMethod();
methodSetAge.invoke(p, age);
System.out.println(p.getAge());
}
private static String extracted(Object p, String propertiesName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
/*
* PropertyDescriptor bp = new PropertyDescriptor(propertiesName,
* p.getClass()); Method methodGetName = bp.getReadMethod(); Object
* readVal = methodGetName.invoke(p); System.out.println(readVal);
*/
BeanInfo beanInfo = Introspector.getBeanInfo(p.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
Object retVal = null;
for (PropertyDescriptor pd : pds) {
if (pd.getName().equals(propertiesName)) {
Method methodGetX = pd.getReadMethod();
retVal = (String) methodGetX.invoke(p);
break;
}
}
return (String) retVal;
}
}
复制代码
问题2.jpg
(113.46 KB, 下载次数: 3)
下载附件
2014-11-5 20:49 上传
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2