Using BeanInfo#getPropertyDescriptors method, we can get all the properties of the bean.
Example
PropertyDescriptor[] propertyDescriptors(final Class<?> c) throws IntrospectionException {
BeanInfo beanInfo = Introspector.getBeanInfo(c);
return beanInfo.getPropertyDescriptors();
}
Above code defines a method propertyDescriptors that retrieves PropertyDescriptor objects for a given class using introspection. It leverages Java's Introspector.getBeanInfo() to obtain class information and then calls getPropertyDescriptors() to retrieve property descriptors. These descriptors provide details about JavaBean properties, aiding dynamic introspection of bean properties at runtime.
Find the below working application.
Employee.java
package com.sample.app.model;
public class Employee {
private static int totalEmployees;
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public static int getTotalemployees() {
return totalEmployees;
}
}
GetPropertiesOfClass.java
package com.sample.app.introspector;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import com.sample.app.model.Employee;
public class GetPropertiesOfClass {
private static PropertyDescriptor[] propertyDescriptors(final Class<?> c) throws IntrospectionException {
BeanInfo beanInfo = Introspector.getBeanInfo(c);
return beanInfo.getPropertyDescriptors();
}
public static void main(String[] args) throws Exception {
PropertyDescriptor[] propertyDescriptors = propertyDescriptors(Employee.class);
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String name = propertyDescriptor.getName();
Class<?> type = propertyDescriptor.getPropertyType();
Method methodToReadThisProperty = propertyDescriptor.getReadMethod();
Method methodToUpdateThisProperty = propertyDescriptor.getWriteMethod();
System.out.println("name : " + name);
System.out.println("type : " + type);
if (methodToReadThisProperty != null) {
System.out.println("methodToReadThisProperty : " + methodToReadThisProperty.getName());
}
if (methodToUpdateThisProperty != null) {
System.out.println("methodToUpdateThisProperty : " + methodToUpdateThisProperty.getName());
}
System.out.println();
}
}
}
Output
name : age type : class java.lang.Integer methodToReadThisProperty : getAge methodToUpdateThisProperty : setAge name : class type : class java.lang.Class methodToReadThisProperty : getClass name : id type : class java.lang.Integer methodToReadThisProperty : getId methodToUpdateThisProperty : setId name : name type : class java.lang.String methodToReadThisProperty : getName methodToUpdateThisProperty : setName
No comments:
Post a Comment