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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!