26 November 2011

Minimal JavaBean introspection example

Just playing with JavaBeans, so here's a small example to create a simple JavaBean, set a property and read it.

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SimpleBean {

  private final String name = "SimpleBean";
  private int size;
  public int getSize() {
    return size;
  }
  public void setSize(int size) {
    this.size = size;
  }
  public String getName() {
    return name;
  }
  
  public static void main(String[] args) throws IntrospectionException {
    SimpleBean sb = new SimpleBean();
    sb.setSize(59);
    BeanInfo bi = Introspector.getBeanInfo(sb.getClass());
    for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
      testGetValue(sb, pd);
    }
  }
  
  public static void testGetValue(Object sb, PropertyDescriptor pd) {
    System.out.print(pd.getName() + "=");
    Method getter = pd.getReadMethod();
    Object arg1[] = {};
    try {
      Object value = getter.invoke(sb, arg1);
      System.out.println(value);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }
}

The output of the program is:

class=class SimpleBean
name=SimpleBean
size=59