java - 从带有类名的字符串中动态调用类变量
问题描述
我正在使用几个类来存储数据。这些类中的每一个都有跨类具有相同名称的静态变量。我想通过使用字符串输入类的名称并从该特定类返回数据来加载这些变量。
我以前通过反射加载类的实例来做到这一点,但我想这样做而不必实际创建类的实例。
public class dataSet {
static int dataPoint=1;
}
public class otherDataSet {
static int dataPoint=2;
}
public int returnDataPoint (string className) {
//returns className.dataPoint
}
解决方案
如果您坚持使用反射,则不必创建类的实例来访问其静态成员。只需使用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
}
推荐阅读
- ios - 用户选择日期后无法显示“今天”而不是今天的日期
- c# - 带有 where 子句的 LINQ 方法语法
- c++ - C++中固定数组和动态分配数组的区别
- scala - SBT 同步在 intellij 上引发错误“无法添加依赖项”
- jquery - Bootstrap (v4.4.1) 折叠不适用于 jQuery (v3.5.0) - 错误:无法将对象转换为原始值
- python - 首次出现后如何为所有下一个日期添加条目
- lisp - 如何从终端在 Mac 上运行 lisp 程序?
- javascript - 第二个组件无法重新加载数据
- android - 未调用作业服务
- c - 结构变量是否默认初始化?