2016-12-23 45 views
-2

因此,在一個類(ImportantClass123)我有這樣的:公共領域 - 你怎麼能得到一個公共領域顯示其名稱(字符串)

public AnotherImportantClass aReallyImportantClass; 

如何退還

AnotherImportantClass 

通過什麼樣的命名爲領域的知識:

aReallyImportantClass 

喜歡的東西

ImportantClass123.getFieldWithName("aReallyImportantClass"); 

我該如何編寫getFieldWithName?它的返回類型是什麼?類?

+0

你需要像反射API,[閱讀](http://stackoverflow.com/questions/160970/如何做 - 我 - invoke - 一個Java方法 - 當給定的方法名字作爲字符串) –

+0

https://docs.oracle.com/javase/tutorial/reflect/member/fieldValues .html – shmosel

+0

@shmosel OP正在尋找字段的類型,而不是數值。令人驚訝的是,我找不到重複的。 –

回答

1

您可以使用反射來獲取該信息。方法Class.getField(String)返回一個Field對象名稱給出的公共字段。與外地對象有一個方法getType(),會給你該字段的類型:

public class Snippet { 
    public Integer x; 

    public static void main(String[] args) throws Exception { 
     Field x = Snippet.class.getField("x"); 
     Class<?> type = x.getType(); 
     System.out.println("Type of field x: " + type); 
    } 
}