2011-08-08 18 views
3

我在寻找类似BeanUtils.describe的工作,但是在.class上工作,而不是对象?有人帮忙吗?目前我正在使用像下面这样的默认getHeaders方法处理对象类的列表。如何在Java中获取.class的所有属性?

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(); 
    } 
} 
+1

注意,你**不能**使用'E.class',也没有“变通”这个,除非* *您可以访问到'以某种方式传递给你的类。 –

+0

@Joachim好点 –

+0

@Sean,我刚刚注意到我想知道“为什么这个标签[标签:泛型]?” ;-) –

回答

10

使用Introspector API:

PropertyDescriptor[] propertyDescriptors = 
    Introspector.getBeanInfo(beanClass).getPropertyDescriptors(); 
List<String> propertyNames = new ArrayList<String>(propertyDescriptors.length); 
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { 
    propertyNames.add(propertyDescriptor.getName()); 
} 
+0

投票了,谢谢 – marioosh

相关问题