如何内省 getter 和 setter 具有不同类型的字段?

How to introspect field for which getter and setter have different types?

我有 JAXB 生成的 Java Beans class,我不想手动更改:

public class Bar
{
  protected Boolean foo;

  public Boolean getFoo() {
     return this.foo;
  }

  public void setFoo(final boolean value) {
     this.foo = value;
  }
}

我正在尝试以这种方式调查此 class(我需要 getter 和 setter):

  PropertyDescriptor[] propertyDescriptiors =
        Introspector.getBeanInfo(Bar.class, Object.class).getPropertyDescriptors();
  for (PropertyDescriptor descriptor : propertyDescriptiors)
  {
     System.out.println("read method: " + descriptor.getReadMethod());
     System.out.println("write method: " + descriptor.getWriteMethod());
  }

但没有找到 setter。

如果我将 getFoo 更改为 return 原始 booleansetFoo 以接收 Boolean 对象,它工作正常。

我怎样才能从这个 class 中获得 getter 和 setter 方法而不改变它们的类型?

你不能,inspector 找不到 setter 因为 foo 类型是 Boolean,而不是 boolean

您可以使用包装器

public class BarWrapper {
    private Bar bar;

    public Boolean getFoo() {
        return this.bar.getFoo();
    }

    public void setFoo(final Boolean value) {
        this.bar.setFoo(value);
    }
}

然后检查包装纸

Introspector.getBeanInfo(BarWrapper.class, Object.class).getPropertyDescriptors();