Creating a Bean Info Class

Introduction

A BeanInfo class can be created from the Interface BeanInfo. The class syntax is as follows: public interface BeanInfo. As the name suggests, the main purpose of the BeanInfo class is to provide the necessary information about the features of the beans used in a code. Oracle describes it as “provides explicit information about the methods, properties, events, and other features of your beans”. When you are developing your bean, it is not required to fill in all the fields given in the BeanInfo class. After you have set the features of your beans as required by your application, the rest of the information of your beans is automatically computed using a low-level reflection of the beans methods.

Some BeanInfo Methods

  • BeanInfo[] getAdditionalBeanInfo() – This method asks the current BeanInfo object to gather information about other BeanInfo objects such that any additional information about the current bean can be retrieved.
  • BeanDescriptor getBeanDescriptor() – This will return the bean descriptor that will provide information about the bean.
  • EventSetDescriptor[] getEventSetDescriptors() – This will return the description of the type of events that use the bean.
  • PropertyDescriptor[] getPropertyDescriptors() – This will return information about all the properties of the bean.
  • int getDefaultEventIndex() – A bean may have a default event that it is associated with or applied when it is used. This will return the event number.
  • int getDefaultpropertyIndex() – Whenever a bean is updated, it might typically have a default property that is most commonly changed.

Example

public static Map<String, String> toStringMap(Object obj)
{
Map<String, String> map = null;
if (obj == null)
{
return map;
}

map = new HashMap<String, String>();
try
{
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors)
{
String key = property.getName();
if (!key.equals("class"))
{
Method getter = property.getReadMethod();
map.put(key, getter.invoke(obj).toString());
}
}
} catch (Exception e) {
map = null;
}
return map;
}

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.