2011-08-08 19 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

相關問題