0

I have two classes as below. In class BBB, I want to pass the variable name (in strVarName variable) I want to access from class AAA. Is it possible to do so?

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 
}
}
SC1986
  • 11
  • 1
  • Does this answer your question? [How to get the fields in an Object via reflection?](https://stackoverflow.com/questions/2989560/how-to-get-the-fields-in-an-object-via-reflection) – dnault Jul 14 '20 at 03:30

1 Answers1

0

You can try using the reflection API as follows:

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();
     }
}
Prashanth D
  • 137
  • 1
  • 6
  • Or you could access the field directly with `Field f = AAA.class.getDeclaredField("strName"); f.setAccessible(true); f.get(objAAA);` – dnault Jul 14 '20 at 03:28