Close

Java - java.beans.Beans Examples

Java 

Creating the instance of the bean using Beans.instantiate(..) and by using information provided by BeanInfo.

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

}
}




See Also