我正在尝试为我拥有的bean类创建一个PropertyDescriptor.我在打电话
new PropertyDescriptor(myProperty, myClass)
Run Code Online (Sandbox Code Playgroud)
并且我看到一个异常,即方法"isMyProperty"不存在.偷看代码 -
/**
* Constructs a PropertyDescriptor for a property that follows
* the standard Java convention by having getFoo and setFoo
* accessor methods. Thus if the argument name is "fred", it will
* assume that the writer method is "setFred" and the reader method
* is "getFred" (or "isFred" for a boolean property). Note that the
* property name should start with a lower case character, which will
* be capitalized in the method names.
*
* @param propertyName The programmatic name of the property.
* @param beanClass The Class object for the target bean. For
* example sun.beans.OurButton.class.
* @exception IntrospectionException if an exception occurs during
* introspection.
*/
public PropertyDescriptor(String propertyName, Class<?> beanClass)
throws IntrospectionException {
this(propertyName, beanClass,
"is" + capitalize(propertyName),
"set" + capitalize(propertyName));
}
Run Code Online (Sandbox Code Playgroud)
文档说它将寻找"getFred",但它总是使用"is" + capitalize(property)!这是在java版本"1.6.0_31"
思考?
编辑:我想我知道你的问题是什么.如果您的类中不存在该属性,那么您将获得"isProperty"方法错误.看我的例子:
{
PropertyDescriptor desc = new PropertyDescriptor("uuid", Company.class);
Method m = desc.getReadMethod();
System.out.println(m.getName()); /* prints getUuid */
}
{
PropertyDescriptor desc = new PropertyDescriptor("uuid11", Company.class);
Method m = desc.getReadMethod();
System.out.println(m.getName()); /* throws Method not found: isUuid11 */
}
Run Code Online (Sandbox Code Playgroud)
原版的:
看起来它只是默认为isProperty作为read方法,如果它不存在,它使用getProperty.看看getReadMethod方法,它的位置:
if (readMethod == null) {
readMethodName = "get" + getBaseName();
Run Code Online (Sandbox Code Playgroud)
所以它首先尝试使用isProperty方法,如果没有该方法,则查找getProperty.
这是完整的方法:
public synchronized Method getReadMethod() {
Method readMethod = getReadMethod0();
if (readMethod == null) {
Class cls = getClass0();
if (cls == null || (readMethodName == null && readMethodRef == null)) {
// The read method was explicitly set to null.
return null;
}
if (readMethodName == null) {
Class type = getPropertyType0();
if (type == boolean.class || type == null) {
readMethodName = "is" + getBaseName();
} else {
readMethodName = "get" + getBaseName();
}
}
// Since there can be multiple write methods but only one getter
// method, find the getter method first so that you know what the
// property type is. For booleans, there can be "is" and "get"
// methods. If an "is" method exists, this is the official
// reader method so look for this one first.
readMethod = Introspector.findMethod(cls, readMethodName, 0);
if (readMethod == null) {
readMethodName = "get" + getBaseName();
readMethod = Introspector.findMethod(cls, readMethodName, 0);
}
try {
setReadMethod(readMethod);
} catch (IntrospectionException ex) {
// fall
}
}
return readMethod;
}
Run Code Online (Sandbox Code Playgroud)