首页 > 解决方案 > 如何在 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 
}
}

标签: java

解决方案


您可以尝试使用反射 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();
     }
}

推荐阅读