3

How to retrieve a static variable using its name dynamically using Java reflection?

If I have class containing some variables:

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; 
 }

And in another class I want variable name is input from user:

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)
}

Using reflection. Any help please?

4

5 回答 5

2

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

(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 回答
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());
            }
        }
    }

}
}
于 2017-05-15T11:52:11.570 回答
0

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

于 2013-07-01T10:15:21.480 回答
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 命名约定。

于 2013-07-01T09:41:53.067 回答
0

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

// 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

于 2013-07-01T10:03:20.187 回答