Search code examples
javajavabeansguavaoption-typeintrospection

JavaBean Introspection with Optional return types


java.beans.Introspector#getBeanInfo

compiles an incomplete PropertyDescriptor when changing the getter return type to com.google.common.base.Optional.

I'm using Java 7 and thus have to use Guava's Optional. I'd like to use it as return types in my JavaBeans. I've prepared these two small unit tests to outline the problem:

import static org.junit.Assert.*;    
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;    
import org.junit.Test;    
import com.google.common.base.Optional;

public class BeanOptionalTest {

  class SimpleBean {
    private String foo;
    public String getFoo() { return foo; }
    public void setFoo(String foo) { this.foo = foo; }
  }

  @Test
  public void test_SimpleBean() throws Exception {
    assertFooProperty(SimpleBean.class);
  }

  class OptionalBean {
    private String foo;
    public Optional<String> getFoo() { return Optional.fromNullable(foo); }
    public void setFoo(String foo) { this.foo = foo; }
  }

  @Test
  public void test_OptionalBean() throws Exception {
    assertFooProperty(OptionalBean.class);
  }

  private void assertFooProperty(Class<?> beanClass) throws IntrospectionException {
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    assertEquals(2, beanInfo.getPropertyDescriptors().length);
    PropertyDescriptor fooDescriptor = beanInfo.getPropertyDescriptors()[1];
    assertNotNull(fooDescriptor.getReadMethod());
    assertEquals("getFoo", fooDescriptor.getReadMethod().getName());
    assertNotNull(fooDescriptor.getWriteMethod());
    assertEquals("setFoo", fooDescriptor.getWriteMethod().getName());
  }
}

test_OptionalBean fails because the write method is null. Presumably the Introspector matches foo to the type Optional instead of String.

How can this behaviour be changed in order to receive a complete PropertyDescriptor despite changing the return type to Optional?


Solution

  • Your test breaks because the type of the parameter of OptionalBean::setFoo doesn't match the return type of OptionalBean::getFoo. A PropertyDescriptor is specific to a type and here, Optional<String> and String are not the same type, even if conceptually they are strongly linked.

    With the current implementation of JavaBeans, you can't do what you want to do. What you could do is write your own BeanInfo-like object that does the introspection for you but doesn't implement BeanInfo.