Close

Java - Introspector Examples

Java 

This example gets BeanInfo with Introspector.getBeanInfo(..) for a given bean class and then discovers all bean features via BeanInfo descriptor getters (subclasses of FeatureDescriptor)

package com.logicbig.example;

import java.beans.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;


public class IntrospectorExample {

public static void main (String[] args) throws IntrospectionException, IOException,
ClassNotFoundException, InvocationTargetException, IllegalAccessException {

//introspecting the details of a target bean
BeanInfo beanInfo = Introspector.getBeanInfo(TheBean.class);

//creating an instance of the bean
TheBean instance = (TheBean) Beans.instantiate(
IntrospectorExample.class.getClassLoader(),
beanInfo.getBeanDescriptor()
.getBeanClass()
.getName());

System.out.println("The instance created : " + instance);

BeanDescriptor bd = beanInfo.getBeanDescriptor();
System.out.println("Bean name: " + bd.getName());
System.out.println("Bean display name: " + bd.getDisplayName());
System.out.println("Bean class: " + bd.getBeanClass());

for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
System.out.println("----------");
System.out.println("Property Name: " + pd.getName());
System.out.println("Property Display Name:" + pd.getDisplayName());
System.out.println("Property Type: " + pd.getPropertyType());

if (pd.getPropertyType()
.isAssignableFrom(java.lang.String.class)) {
System.out.println("Property value: " + pd.getReadMethod()
.invoke(instance));
pd.getWriteMethod()
.invoke(instance, "a string value set");
System.out.println("Property value after setting: " + pd.getReadMethod()
.invoke(instance));
}
}

//similarly we can analyse bean's method, event etc..
}

public static class TheBean {
private String someStr;

public String getSomeStr () {
return someStr;
}

public void setSomeStr (String someStr) {
this.someStr = someStr;
}

}
}

Output:

 The instance created : com.logicbig.example.IntrospectorExample$TheBean@6d6f6e28
Bean name: IntrospectorExample$TheBean
Bean display name: IntrospectorExample$TheBean
Bean class: class com.logicbig.example.IntrospectorExample$TheBean
----------
Property Name: class
Property Display Name:class
Property Type: class java.lang.Class
----------
Property Name: someStr
Property Display Name:someStr
Property Type: class java.lang.String
Property value: null
Property value after setting: a string value set




See Also