How to retrieve Java Bean Metadata
-
Now, The question is How to retrieve the information about a given java bean class(I mean compiled class). That information is also known as Metadata:
- Naming Conventions
- By writing an additional class that extends the BeanInfo interface
There are again 2 ways! And its based on how we have describe the Bean. As seen in previous tutorial – Link
We have 2 methods to describe a Bean.
1. Naming Conventions.
import java.beans.*;
public class EmpIntrospector
{
public static void main(String args[])
{
try
{
Class c = Class.forName("Employee");
BeanInfo beanInfo = Introspector.getBeanInfo(c);
System.out.println("Properties:");
PropertyDescriptor propertyDescriptor[] = beanInfo.getPropertyDescriptors();
for(int i = 0; i < propertyDescriptor.length; i++)
{
System.out.println("\t" + propertyDescriptor[i].getName());
}
System.out.println("Events:");
EventSetDescriptor eventSetDescriptor[] = beanInfo.getEventSetDescriptors();
for(int i = 0; i < eventSetDescriptor.length; i++)
{
System.out.println("\t" + eventSetDescriptor[i].getName());
}
}
catch(Exception e)
{
System.out.println("Exception caught. " + e);
}
}
}
In above sample code we are retrieving metadata by getting propertyDescriptor[] / eventDescriptopr[] using beanInfo Interface.
2. By writing an additional class that extends the BeanInfo interface.
import java.beans.*;
public class EmpIntrospector2
{
public static void main(String args[])
{
try
{
Class c = Class.forName("Employee");
BeanInfo beanInfo = Introspector.getBeanInfo(c);
System.out.println("Properties:");
PropertyDescriptor propertyDescriptor[] = new EmployeeBeanInfo().getPropertyDescriptors();
for(int i = 0; i < propertyDescriptor.length; i++)
{
System.out.println("\t" + propertyDescriptor[i].getName());
}
System.out.println("Events:");
EventSetDescriptor eventSetDescriptor[] = new EmployeeBeanInfo().getEventDescriptors();
for(int i = 0; i < eventSetDescriptor.length; i++)
{
System.out.println("\t" + eventSetDescriptor[i].getName());
}
}
catch(Exception e)
{
System.out.println("Exception caught. " + e);
}
}
}
In above sample code we are retrieving metadata by getting propertyDescriptor[] / eventDescriptopr[] using our defined class “EmployeeBeanInfo” which was describing Employee bean.




Recent Comments