1

我已经定义了一个具有以下属性的 Employee 对象

public class Employee {

    private String id;
    private String name;
    private Address address;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
}

地址对象:

public class Address {

    private String street;
    private String city;

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

并为属性生成了 getter 和 setter。当我对属性执行以下操作时:

String value = BeanUtils.getNestedProperty(employee, "address.street");

我得到 address.street 的“无此类方法异常”。

java.lang.NoSuchMethodException:类“com.test.xm.Employee”上的未知属性“address.street”

字段 id 和 name 工作正常。

仔细检查了getter和setter,看起来很好。我可能在这里做错了什么?

编辑:更新了 getter 和 setter。

4

1 回答 1

4

Use PropertyUtils instead of BeanUtils.

   (String) PropertyUtilsBean.getInstance().getNestedProperty(employee, "address.street");  

For me your example is working well too. So in your example, the only possible error is: employee isn't an instance of Employee.

Also why don't you post the Exception message? They contain very helpful information, for eg:

 java.lang.NoSuchMethodException: Unknown property 'address' on class 'class com.mycompany.dto.Address'
于 2012-12-17T18:57:43.690 回答