beans
List bean property names
With this example we are going to demonstrate how to list the names of a bean’s properties. We are using the PropertyDescriptor, a class that describes one property that a Java Bean exports via a pair of accessor methods. We are also using the Introspector class, that provides a standard way for tools to learn about the properties, events, and methods supported by a target Java Bean. In short, to list the names of a bean’s properties you should:
- Create a simple class, like
Bean
class in the example. It has two String properties and getters and setters for the properties. - Use
getBeanInfo(Class<?> beanClass)
API method of Introspector on theBean
to learn about all its properties, exposed methods, and events. The method returns a BeanInfo, that provides explicit information about the methods, properties, events, etc, of the bean. - Use
getPropertyDescriptors()
API method of BeanInfo to get a list with all the PropertyDescriptors for all properties of the bean. - Use
getName()
andgetPropertyType()
API method of PropertyDescriptor to get name and the Java type of each property.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; public class ListBeanPropertyNames { public static void main(String[] args) throws Exception { BeanInfo beanInfo = Introspector.getBeanInfo(Bean.class); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (int i=0; i<descriptors.length; i++) { String propName = descriptors[i].getName(); Class<?> propType = descriptors[i].getPropertyType(); System.out.println("Property with Name: " + propName + " and Type: " + propType); } } public static class Bean { // Property property1 private String property1; // Property property2 private int property2; public String getProperty1() { return property1; } public void setProperty1(String property1) { this.property1 = property1; } public int getProperty2() { return property2; } public void setProperty2(int property2) { this.property2 = property2; } } }
Output:
Property with Name: class and Type: class java.lang.Class
Property with Name: property1 and Type: class java.lang.String
Property with Name: property2 and Type: int
This was an example of how to list the names of a bean’s properties in Java.