How To Get Bean Property Details In Java

Java API jabs java.bean package for working with the Java beans and its properties. In our previous example I have explained how to write bean PropertyChangeListener. This example is just an extension to that post and it provides the sample for getting the property method details. Lets look at the example.

BeanPropertyDetails.java

package javabeat.net.core;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

/**
 * Bean property details example
 *
 */
public class BeanPropertyDetails {
	public static void main(String[] args) {
		BeanInfo beanInfo = null;
		try {
			beanInfo = Introspector.getBeanInfo(Bean.class);
		} catch (IntrospectionException exception) {
			exception.printStackTrace();
		}
		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);
		}

	}
}

Bean.java

package javabeat.net.core;

public class Bean {
	private int id;
	private String name;
	private String city;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}
}

Output…

Property with Name: city and Type: class java.lang.String
Property with Name: class and Type: class java.lang.Class
Property with Name: id and Type: int
Property with Name: name and Type: class java.lang.String

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*