Reputation: 33
I cannot get the property with underscore (ex: User_Name) from a class using BeanUtils.getProperty(bean, property)
, it always throw error:
"Unknown property 'User_Name' on class 'User'".
But when I debug the bean, it has User_Name property.
BeanUtils.getProperty(bean, propertyName);
The User class is
public class User {
private String ID;
private String User_Name;
public void setID(String ID) {
this.ID = ID;
}
public String getUser_Name() {
return this.User_Name;
}
public void setUser_Name(String user_Name) {
this.User_Name = user_Name;
}
}
Upvotes: 1
Views: 1217
Reputation: 8114
It is a matter of naming convention. You can refer to Where is the JavaBean property naming convention defined? for reference. From section 8.8 of JavaBeans API specification
... Thus when we extract a property or event name from the middle of an existing Java name, we normally convert the first character to lower case*case 1. However to support the occasional use of all upper-case names, we check if the first two characters*case 2 of the name are both upper case and if so leave it alone. So for example,
'FooBah" becomes 'fooBah'
'Z' becomes 'z'
'URL' becomes 'URL'We provide a method Introspector.decapitalize which implements this conversion rule
Hence for your given class, the property deduced from getUser_Name()
and setUser_Name()
is "user_Name" instead of "User_Name" according to *case1. And calling getProperty(bean, "ID")
is working according to *case 2.
To solve the problem, please update the naming according to the Java naming convention, we should start with lower case for property and method, and use camelCase instead of snake_case to separate word. Keep in mind that following convention is really important in programming. The following is the updated class as an example.
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
public class User {
private String ID;
private String userName;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public static void main(String[] args)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
User bean = new User();
bean.setUserName("name");
System.out.println(BeanUtils.getProperty(bean, "userName"));
}
}
Upvotes: 3