首页 > 解决方案 > 从带有类名的字符串中动态调用类变量

问题描述

我正在使用几个类来存储数据。这些类中的每一个都有跨类具有相同名称的静态变量。我想通过使用字符串输入类的名称并从该特定类返回数据来加载这些变量。

我以前通过反射加载类的实例来做到这一点,但我想这样做而不必实际创建类的实例。

public class dataSet {
static int dataPoint=1;
}
public class otherDataSet {
static int dataPoint=2;
} 
public int returnDataPoint (string className) {
//returns className.dataPoint
}

标签: java

解决方案


如果您坚持使用反射,则不必创建类的实例来访问其静态成员。只需使用null而不是对象。

public class dataSet {
static int dataPoint=1;
}
public class otherDataSet {
static int dataPoint=2;
} 

// You can try-catch inside of the method or put a throws declaration on it. Your choice.
public int returnDataPoint (string className) throws Exception {
    Class<?> clazz = Class.forName(className); // edit to include package if needed
    Field field = clazz.getField("dataPoint");
    return field.getInt(null); // calling with null
}

推荐阅读