我知道commons-beanutils期望Java类在理想情况下应符合Java Beans命名模式。但是当他们不遵守命名约定时,我会看到库结果因字段声明的不同方式而异。
因此,当我声明F_NAME或MiddleName之类的内容时,使用BeanUtils.setProperty()设置属性值时,它将值设置为null,而当使用PropertyUtils.getSimpleProperty()读取同一属性时,它将引发异常:
Exception in thread "main" java.lang.NoSuchMethodException: Unknown property 'F_NAME' on class...
另一方面,当我将字段声明为LNAME时,BeanUtils.setProperty()和PropertyUtils.getSimpleProperty()都可以正常工作。
示例代码:
public final class PropertyUtilsTest {
private String F_NAME;
private String MiddleName;
private String LNAME;
/**
* @return the F_NAME
*/
public String getF_NAME() {
return F_NAME;
}
/**
* @param F_NAME the f_NAME to set
*/
public void setF_NAME(String f_NAME) {
F_NAME = f_NAME;
}
/**
* @return the middleName
*/
public String getMiddleName() {
return MiddleName;
}
/**
* @param middleName the middleName to set
*/
public void setMiddleName(String middleName) {
MiddleName = middleName;
}
/**
* @return the LNAME
*/
public String getLNAME() {
return LNAME;
}
/**
* @param lNAME the LNAME to set
*/
public void setLNAME(String lNAME) {
LNAME = lNAME;
}
public static void main(String[] args) throws Exception {
PropertyUtilsTest l_obj = new PropertyUtilsTest();
BeanUtils.setProperty(l_obj, "LNAME", "Future");
BeanUtils.setProperty(l_obj, "F_NAME", "Wambling");
BeanUtils.setProperty(l_obj, "MiddleName", "Uknown");
System.out.println("F_NAME:: " + l_obj.getF_NAME());
System.out.println("MiddleName:: " + l_obj.getMiddleName());
System.out.println("LNAME:: " + l_obj.getLNAME());
try {
System.out.println("MiddleName:: " + PropertyUtils.getSimpleProperty(l_obj, "MiddleName"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("\n");
try {
System.out.println("F_NAME:: " + PropertyUtils.getSimpleProperty(l_obj, "F_NAME"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("LNAME:: " + PropertyUtils.getSimpleProperty(l_obj, "LNAME"));
System.out.println("\n");
}
}
输出:
F_NAME:: null
MiddleName:: null
LNAME:: Future
java.lang.NoSuchMethodException: Unknown property 'MiddleName' on class 'class com.wambling.stubs.PropertyUtilsTest'
at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1269)
at org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(PropertyUtils.java:649)
at com.wambling.stubs.PropertyUtilsTest.main(PropertyUtilsTest.java:72)
java.lang.NoSuchMethodException: Unknown property 'F_NAME' on class 'class com.wambling.stubs.PropertyUtilsTest'
at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1269)
at org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(PropertyUtils.java:649)
at com.wambling.stubs.PropertyUtilsTest.main(PropertyUtilsTest.java:78)
LNAME:: Future
所以,我的问题是为什么这些字段的行为如此不同,因为它们都不遵循Java Beans Naming约定。
commons-beanutils使用的版本:1.9.3
PS:如果我将F_NAME更改为f_NAME,并将MiddleName更改为MiddleName,则整个代码都可以正常工作。