Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all properties of .class in Java?

Tags:

java

generics

I'm searching for something that works like BeanUtils.describe, but working on .class, not object ? Anybody help ? Currently i'm working on list of objects class with default getHeaders method like below.

public class SimpleList<E>  {
    protected final Class<E> clazz;

    SimpleList(Class<E> clazz) {
        this.clazz = clazz;
    }

    public String[] getHeaders() {
        Map props = BeanUtils.describe(clazz); // replace this with something
        return (String[]) props.keySet().toArray();
    }
}
like image 991
marioosh Avatar asked Dec 05 '22 20:12

marioosh


2 Answers

Use the Introspector API:

PropertyDescriptor[] propertyDescriptors = 
    Introspector.getBeanInfo(beanClass).getPropertyDescriptors();
List<String> propertyNames = new ArrayList<String>(propertyDescriptors.length);
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
    propertyNames.add(propertyDescriptor.getName());
}
like image 56
Sean Patrick Floyd Avatar answered Dec 23 '22 11:12

Sean Patrick Floyd


You pretty much want PropertyUtils.getPropertyDescriptors(). It returns an array of PropertyDescriptor objects, of which you'd need to extract the names.

like image 39
Joachim Sauer Avatar answered Dec 23 '22 10:12

Joachim Sauer