Why does PropertyDescriptor return a property name with uppercase as first character?

蓝咒 提交于 2019-12-03 16:22:38

This is actually the documented behaviour.

First of all, property names are entirely located by discovering their getter and setter, and not by looking at the fields of the class. This is specified in paragraph 8.3 of the Java Beans specification:

If we discover a matching pair of get<PropertyName> and set<PropertyName> methods that take and return the same type, then we regard these methods as defining a read-write property whose name will be <propertyName>.

So when you have the introspection of a class that contains Long getRPersonId() and setRPersonId(Long), a property can be extracted from it. The name of the property generally follows from lower-casing the first letter, and keeping the rest unchanged. But this is not always the case, the exact rule is in paragraph 8.8:

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. However to support the occasional use of all upper-case names, we check if the first two characters 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.

In the example above, the getter and setter would provide the String RPersonId to turn into a property name. Since the first two characters are upper-case, the first character will not be lower-cased. As such, the property name that will be derived is RPersonId, and this explains your output.

You can also call the method decapitalize to see which property name would be located from a pair of getter / setter:

System.out.println(Introspector.decapitalize("RPersonId"));     // prints RPersonId
System.out.println(Introspector.decapitalize("PersonAddress")); // prints personAddress

Because this is part religion.

The people who did Java Beans felt that properties should ALWAYS be accessed by a pair of methods. So you are NOT getting the name of the data member. You are getting the property which can only be accessed by the methods.

This is from the documentation:

A PropertyDescriptor describes one property that a Java Bean exports 
via a pair of accessor methods.

https://docs.oracle.com/javase/7/docs/api/java/beans/PropertyDescriptor.html

The theory was you should never use the data member name, and so through the Bean interface, they don't give you that.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!