3

Javaリフレクションを使用してその名前を動的に使用して静的変数を取得する方法は?

いくつかの変数を含むクラスがある場合:

public class myClass { 
     final public static string [][] cfg1= {{"01"},{"02"},{"81"},{"82"}}; 
     final public static string [][]cfg2=  {{"c01"},{"c02"},{"c81"},{"c82"}}; 
     final public static string [][] cfg3=  {{"d01"},{"d02"},{"d81"}{"d82"}}; 
     final public static int cfg11 = 5; 
     final public static int cfg22 = 10; 
     final public static int cfg33 = 15; 
 }

そして、別のクラスでは、変数名をユーザーから入力したい:

class test { 
   Scanner in = new Scanner(System.in); 
   String userInput = in.nextLine();  
    // get variable from class myClass that  has the same name as userInput
   System.out.println("variable name " + // correct variable from class)
}

リフレクションの使用。何か助けてください。

4

5 に答える 5

2

Java Reflect を使用する必要があります。これがサンプルコードです。たとえば、Java リフレクションを使用して「cfg1」変数にアクセスし、それをコンソールに出力しました。main メソッドをよく調べてください。単純化のために例外を処理していません。ここでの重要な行は次のとおりです。

(String[][]) MyClass.class.getField("cfg1").get(MyClass.class);

__ ^typecast__ ^accessingFeild______________ ^accessFromClassDefinition

public class MyClass {
    final public static String[][] cfg1 = { { "01" }, { "02" }, { "81" },
            { "82" } };
    final public static String[][] cfg2 = { { "c01" }, { "c02" }, { "c81" },
            { "c82" } };
    final public static String[][] cfg3 = { { "d01" }, { "d02" }, { "d81" },
            { "d82" } };
    final public static int cfg11 = 5;
    final public static int cfg22 = 10;
    final public static int cfg33 = 15;

    public static void main(String[] args) throws IllegalArgumentException,
            IllegalAccessException, NoSuchFieldException, SecurityException {

        String[][] str = (String[][]) MyClass.class.getField("cfg1").get(
                MyClass.class);

        for (String[] strings : str) {
            for (String string : strings) {
                System.out.println(string);
            }
        }

    }
}
于 2015-10-05T06:37:46.317 に答える
0

Class.getField()またはClass.getDeclaredField()を呼び出してField.getValue()から結果を呼び出し、静的変数の場合はパラメーターとして null (またはクラス自体) を指定し、インスタンス変数の場合はクラスのインスタンスを指定します。

于 2013-07-01T10:15:21.480 に答える