使用名称检索静态变量,并使用反射动态检索



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

使用反射。请帮忙吗?

您需要使用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);
            }
        }
    }
}

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

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

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

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

您可以尝试以下操作:

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

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

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

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

相关内容

  • 没有找到相关文章

最新更新