为什么 PropertyDescriptor(String, Class) 构造函数使用 isFieldName() 作为 getter 名称?

Why PropertyDescriptor(String, Class) constructor uses isFieldName() as the getter name?

我希望构造函数同时测试 getFieldName() 和 isFieldName() getter。为什么 IS_PREFIX 默认前缀?

源代码:http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/beans/PropertyDescriptor.java#PropertyDescriptor.%3Cinit%3E%28java.lang.String%2Cjava.lang.Class%29

我用的是Java1.8.0_31_b13.

我如何使用它:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.beans.PropertyDescriptor;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    class Foo { String bar; public String getBar(){return bar;} public void setBar(String b){this.bar=b;} }

    public static void main (String[] args) throws java.lang.Exception
    {
        java.beans.PropertyDescriptor p = new java.beans.PropertyDescriptor("bar", Foo.class);
        System.out.println(p.getReadMethod().getName()); // prints getBar, not consistent with source code
    }
}

https://ideone.com/5pm0lA

代码打印 getBar 但我不明白为什么。

The code prints getBar but I don't get why.

javadoc 指出

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).

您提供了 barpropertyName,您的 class 有一个名为 getBar 的可访问访问器,这就是返回的内容。

I would expect the constructor to test for both getFieldName() and isFieldName() getters. Why is IS_PREFIX the default prefix?

您可以访问源代码,我们去兔子洞吧。具体看getReadMethod方法的逻辑。如果找到带有 get 前缀的 getter,则构造函数中设置的前缀将在该方法中被覆盖。


题前改动:

您的访问器和修改器不是 publicPropertyDescriptor 首先尝试使用 get/set 前缀(遵循约定)查找 public getter/setter,然后尝试使用 is 查找 boolean 属性。错误消息只是告诉您它最后尝试的操作。

制作你的属性public.