Category Archives: Introspector

Java Introspection

What JavaBeans know about them selves.

In another article I already wrote about JavaBeans and briefly mentioned Introspection. In this post I include a more advanced example of Introspection. The example below uses the Introspector class which provides a standard way for tools to learn about the properties, events, and methods supported by a target JavaBean.
For each of those three kinds of information, the Introspector will separately analyze the bean’s class and superclasses looking for either explicit or implicit information and use that information to build a BeanInfo object that comprehensively describes the target bean:

try {
    BeanInfo bi = Introspector.getBeanInfo(MyBean.class);
    PropertyDescriptor[] pds = bi.getPropertyDescriptors();
    for (int i=0; i<pds.length; i++) {
        // Get property name
        String propName = pds[i].getName();
    }
    // class, prop1, prop2, PROP3
} catch (java.beans.IntrospectionException e) {
}

public class MyBean {
    // Property prop1
    public String getProp1() {
        return null;
    }
    public void setProp1(String s) {
    }

    // Property prop2
    public int getProp2() {
        return 0;
    }
    public void setProp2(int i) {
    }

    // Property PROP
    public byte[] getPROP3() {
        return null;
    }
    public void setPROP3(byte[] bytes) {
    }
}