NoSuchMethodError of BeanUtils.copyProperty(due to wrong access level)

为了节省开发时间,今天打算做一个数据集合类,可以直接将java中的ResultSet,或者其他Collection派生类的内容copy到该集合中,然后加入自定义的一些方法,比如支持直接导出Excel、CSV、KDF、Image、HTML等。这里借助Apache Commons BeanUtils的和反射(Reflection),将数据库中的一行记录保存为一个对象,然后插入数据集中,结果老是报错如下:

USING CONVERTER org.apache.commons.beanutils.converters.IntegerConverter@1befab0
java.lang.reflect.InvocationTargetException: Cannot set id
at org.apache.commons.beanutils.BeanUtilsBean.copyProperty(BeanUtilsBean.java:449)
at org.apache.commons.beanutils.BeanUtils.copyProperty(BeanUtils.java:129)

… …
Caused by: java.lang.NoSuchMethodException: Property ‘id’ has no setter method
at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1746)
at org.apache.commons.beanutils.BeanUtilsBean.copyProperty(BeanUtilsBean.java:447)

代码段如下:

private void dumpResultSet(ResultSet rs, Class clazz) throws Exception {
	ResultSetMetaData metaData = (ResultSetMetaData) rs.getMetaData();
	int colCnt = metaData.getColumnCount();
	Field[] fields = clazz.getDeclaredFields();

	while (rs.next()) {
		Object newInstance = clazz.newInstance();

		for (int i = 1; i <= colCnt; i++) {
			try {
				Object value = rs.getObject(i);
				for (int j = 0; j < fields.length; j++) {
					Field f = fields[j];
					if (f.getName().equalsIgnoreCase(
							metaData.getColumnName(i).replaceAll("_", ""))) {

						log.info("f.getName:" + f.getName());

						BeanUtils.copyProperty(newInstance, f.getName(),
								value);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		list.add(newInstance);
	}
}

The root cause: public is required for class UserInfo, or else you’ll get the ‘NoSuchMethodError‘ exception, DO NOT ignore the access level

public class UserInfo {
	private int id;
	private String user;
	private String password;

	public UserInfo() {
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getId() {
		return id;
	}

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

Eclipse一直提示:NoSuchMethodError,可是UserInfo里面明明有对应的setter方法,最后,才鬼使神差的发现,只要将UserInfo整个类声明为public就可以了。我一直都把注意力放到是否把setter和getter设置为public,却忽略了Bean的访问级别,希望碰到类似问题的朋友可以注意一下。

[ad]

Leave a Reply




 

Switch to our mobile site