使用反射动态地使用其名称检索静态变量

时间:2013-07-01 09:37:50

标签: java reflection

如何使用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)
}

使用反射。有什么帮助吗?

5 个答案:

答案 0 :(得分:1)

你需要利用java反射。这是一个示例代码。例如,我访问了cfg1'变量使用java反射,然后将其打印到控制台中。仔细研究主要方法。我没有处理简化的例外。这里的关键是:

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

__ ^ typecast__ ^ accessFeild ______________ ^ 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);
            }
        }

    }
}

答案 1 :(得分:1)

我合并上述两个解决方案并得到:

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;

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
{

    for (Field field : MyClass.class.getDeclaredFields()) {
        if (!Modifier.isStatic(field.getModifiers())) {
            System.out.println("Non-static field: " + field.getName());
        }
        else {
            System.out.println("Static field: " + field.getName());
            Object obj = MyClass.class.getField(field.getName()).get(MyClass.class);
            if (obj instanceof String[][]) {
                String[][] cad = (String[][]) obj;
                for (String[] strings : cad) {
                    System.out.println("Values:: " + Arrays.toString(strings));
                }
            }
            else {
                System.out.println("  " + obj.toString());
            }
        }
    }

}
}

答案 2 :(得分:0)

您可以尝试这样的事情:

for (Field field : myClass.class.getDeclaredFields()) {
    if (!Modifier.isStatic(field.getModifiers())) {
        System.out.println("Non-static field: " + field.getName());              
    }
    else {
        System.out.println("Static field: " + field.getName());
    }
}

使用Field#get(Object obj)获取值。

注意:请遵循Java命名约定。

答案 3 :(得分:0)

只需调用Class.getField()Class.getDeclaredField(),然后在结果上调用Field.getValue(),在静态变量或实例的情况下提供null(或类本身)作为参数在实例变量的情况下的类。

答案 4 :(得分:-1)

如果我很了解你的需求,这可能适合他们:

// user input, hardcoded for the example
String fieldName = "cfg22";

MyClass blank = new MyClass();
Object value = null;
try {
    value = MyClass.class.getDeclaredField(fieldName).get(blank);
} catch (IllegalArgumentException e) {
    // if the specified object is not an instance of the class or
    // interface declaring the underlying field (or a subclass or
    // implementor thereof)
    e.printStackTrace();
} catch (SecurityException e) {
    // if a security manager, s, is present [and restricts the access to
    // the field]
    e.printStackTrace();
} catch (IllegalAccessException e) {
    // if the underlying field is inaccessible
    e.printStackTrace();
} catch (NoSuchFieldException e) {
    // if a field with the specified name is not found
    e.printStackTrace();
}

System.out.println(value);

打印10