一、问题

最近在使用PropertyUtils类处理对象属性时,遇到以下错误:

Exception in thread "main" java.lang.NoSuchMethodException:

Property 'name' has no getter method in class 'class xxx'

由于是自己测试的代码,就把用到的类写到同一个Java文件中了,代码如下:

package com.test;

import org.apache.commons.beanutils.PropertyUtils;

public class Country {

    private City city;
    public City getCity() {
        return city;
    }
    public void setCity(City city) {
        this.city = city;
    }
    
    public static void main(String[] args) throws Exception {
        Country country = new Country();
        City city = new City();
        city.setName("BeiJing");
        country.setCity(city);
        Object cityName = PropertyUtils.getNestedProperty(country, "city.name");
        System.out.println(cityName);
    }
}

class City{
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

运行此类时报以下错误:

Exception in thread "main" java.lang.NoSuchMethodException: Property 'name' has no getter method in class 'class com.test.City'
	at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1274)
	at org.apache.commons.beanutils.PropertyUtilsBean.getNestedProperty(PropertyUtilsBean.java:808)
	at org.apache.commons.beanutils.PropertyUtilsBean.getProperty(PropertyUtilsBean.java:884)
	at org.apache.commons.beanutils.PropertyUtils.getProperty(PropertyUtils.java:464)
	at com.test.Country.main(Country.java:20)

二、分析

由于City类中确实有name属性的getter方法,于是上网查找,网上说这是个很怪的异常,可能来自以下3个原因:

  • 类需要定义为public

  • 类可能需要定义一个包

  • Bean类需要序列化

三、解决方法

City类单独保存为Java文件。