1

我不熟悉 java bean 框架,在下面的场景中,我得到了方法 getFooWithX 的 IndexedPropertyDescriptor,有人可以解释为什么吗?

public class IntrospectorTest {
public static void main(String[] args) throws IntrospectionException {
    BeanInfo info = Introspector.getBeanInfo(SubClass.class);
    PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
    for (int i = 0; i < descriptors.length; i++) {
        System.out.println(descriptors[i].getClass().getName() + ":" + descriptors[i].getName());
    }
}

}

abstract class BaseClass {
public abstract Object getFoo();

}

abstract class SubClass extends BaseClass {
public Object getFooWithX(int x) {
    return null;
}

}

结果将是:

java.beans.PropertyDescriptor:class
java.beans.PropertyDescriptor:foo
java.beans.IndexedPropertyDescriptor:fooWithX

为什么?

4

1 回答 1

1

If a method is named getX with no arguments, it is taken to be a getter for a non-indexed property X. If a method is named getX with a single int argument, it is taken to be a getter for an indexed property X. That is why you get the IndexedPropertyDescriptor returned.

An indexed property is a property which is an array, indexed by an integer. For example, if a user can have multiple nicknames, and public String getNickNames(int n) returns their *n*th nickname, then "nickNames" is an indexed property. There should also be a public String[] getNickNames() to return all nickNames at once, but the Introspector will still identify an indexed property even if no such method exists.

Whether this is appropriate depends on semantically what "getFooWithX" means. If "fooWithX" is meant to be an array and the parameter is an index used to select an element, then this semantically makes sense. If the parameter is something other than an index into an array, then it would be advisable to rename the method to not start with "get" if that is possible.

于 2013-07-03T11:57:46.317 回答