- package zhangTech;
- import java.beans.IntrospectionException;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import org.apache.commons.beanutils.BeanUtils;
- /*
- * 定义一个标准的JavaBean,名叫Person,包含属性name、age。使用反射的方式创
- 建一个实例、调用构造函数初始化name、age,使用反射方式调用setName方法对名称进
- 行设置,不使用setAge方法直接使用反射方式对age赋值。
- */
- class Person
- {
- public String name;
- private int age;
- public Person(String name, int age) {
- this.name = name;
- this.age = 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 BeanDemo {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Class<Person> cls=Person.class;//获取字节码
-
- String propertyName="name";
- String name="yu";
- String propertyAge="age";
- int age=22;
- Person p;
-
- try{
- Constructor<Person> con=cls.getConstructor(String.class,int.class);
- p=con.newInstance("zhang",20);
-
- //调用方法设置年龄和姓名属性值
- mSetName( p, propertyName, name);
- mSetAge(p ,propertyAge,age );
- System.out.println(p.getName()+"--"+p.getAge());
-
- BeanUtils.setProperty(p, propertyName, name);//这里一用就报错啊,为啥?
- System.out.println(BeanUtils.getProperty(p, propertyName));//这列也是报错,求指导
- }catch(Exception e){
- e.printStackTrace();
- }
-
- }
- private static void mSetName(Person p ,String propertyName, String name
- ) throws IntrospectionException, IllegalAccessException,
- InvocationTargetException {
- PropertyDescriptor pd=new PropertyDescriptor(propertyName, p.getClass());
- Method methodSetName=pd.getWriteMethod();
- methodSetName.invoke(p, name);
- }
- private static void mSetAge(Person p,String propertyAge,int age)
- throws IntrospectionException, IllegalAccessException,
- InvocationTargetException {
- PropertyDescriptor pd=new PropertyDescriptor(propertyAge, p.getClass());
- Method methodSetAge=pd.getWriteMethod();
- methodSetAge.invoke(p, age);
- }
- }
复制代码 为什么用BeanUtils就报错啊,搞不明白了下,面是错误信息:求指导啊- yu--22
- java.lang.reflect.InvocationTargetException: Cannot set name
- at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1017)
- at org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:456)
- at zhangTech.BeanDemo.main(BeanDemo.java:61)
- Caused by: java.lang.NoSuchMethodException: Property 'name' has no setter method in class 'class zhangTech.Person'
- at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:2128)
- at org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1948)
- at org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:2054)
- at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1015)
- ... 2 more
复制代码
|
|