Line
Line

Reputation: 1651

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

I have JAXB-generated Java Beans class which I do not want to change by hand:

public class Bar
{
  protected Boolean foo;

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

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

I'm trying to investigate this class (I need getter and setter) in this way:

  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());
  }

but it doesn't find setter.

If I change getFoo to return primitive boolean or setFoo to receive Boolean object, it works fine.

What can I do to get both getter and setter method from this class without changing their types?

Upvotes: 1

Views: 501

Answers (1)

Luca Montagnoli
Luca Montagnoli

Reputation: 302

You can't, inspector can't find setter because foo type is Boolean, not boolean.

You could use a wrapper

public class BarWrapper {
    private Bar bar;

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

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

and then inspect on the wrapper

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

Upvotes: 3

Related Questions