2016-12-23 10 views
-2

(ImportantClass123)私はこれ持っている:私は返すにはどうすればよいパブリックフィールドあなたは、その名前気力パブリックフィールドを取得できます(文字列)クラスでとても

public AnotherImportantClass aReallyImportantClass; 

AnotherImportantClass 

そのフィールドとして名前何の知識経由:

aReallyImportantClass 

0123のような何か
ImportantClass123.getFieldWithName("aReallyImportantClass"); 

getFieldWithNameはどのように記述しますか?戻り値の型は何でしょうか?クラス?

+0

あなたはリフレクションAPIのようなものが必要になります、[この記事を読む](http://stackoverflow.com/questions/160970/:とフィールドオブジェクトを使用すると、そのフィールドの種類を与える方法getType()を持っていますメソッド名をas-a-stringと指定した場合の-i-invoke-a-java-method) –

+0

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

+0

@shmosel OPは、値ではなくフィールドのタイプを探しています。驚いたことに、私はそのための重複を見つけることができません。 –

答えて

1

リフレクションを使用してその情報にアクセスできます。メソッドClass.getField(String)は、名前によって与えられたpublicフィールドのオブジェクトFieldを返します。

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); 
    } 
} 
関連する問題