java - 如何在 Java 中使用字符串调用类的变量
问题描述
我有两个类如下。在 BBB 类中,我想传递我想从 AAA 类访问的变量名(在 strVarName 变量中)。有可能这样做吗?
public class AAA{
String strName = "SomeName";
String strAddress = "SomeAddress";
String strPhone = "1231234567";
public static void main(String[] args) {
int intTest;
intTest = 10/2;
System.out.println (intTest)
}
}
public class BBB{
public static void main(String[] args) {
String strVarName;
strVarName = "strName";
AAA objAAA = new AAA();
System.out.println(objAAA.strVarName);//How to achive this line of code
}
}
解决方案
您可以尝试使用反射 API,如下所示:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class AAA{
String strName = "SomeName";
String strAddress = "SomeAddress";
String strPhone = "1231234567";
public String getStrName() {
return strName;
}
}
class BBB{
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
String strVarName;
strVarName = "strName";
AAA objAAA = new Test();
Method method = objAAA.getClass().getMethod(createGetterName(strVarName));
Object result = method.invoke(objAAA);
System.out.println(result.toString());
}
private static String createGetterName(String name) {
StringBuilder sb = new StringBuilder("get");
sb.append(name.substring(0, 1).toUpperCase());
sb.append(name.substring(1));
return sb.toString();
}
}
推荐阅读
- r - 绘制一个值在 ggplot 的列中出现的次数
- apache-spark-sql - Spark SQL - 将 SHA1 转换为 BIGINT
- java - 配置客户端在 Spring Boot 中不起作用
- stored-procedures - 在 Dataflow 中调用 BQ 存储过程
- python - 树状图:ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
- c# - 将 asp.net core 2.2 项目迁移到版本 3.1 后分析器异常
- tensorflow - 训练后模型的最后状态是什么?
- javascript - 如何从鼠标的最后一个位置到鼠标的当前位置画一条线?
- node.js - 如何从谷歌分析多渠道渠道请求数据
- python - 在 python 中使用鼠尾草