1

I was wondering, if it's possible to call a variable of other class by passing value to object from another variable.

Something like this:

class Foo {
   public String classVar = "hello";
} 

then we make a object of the class :

Foo bin = new Foo();

Now, I know we can use var by :

bin.classVar;

But, suppose value classVar is in another string variable :

Foo bin = new Foo();    
String var2 = "classVar";
bin.var2 ??????????

How to achieve this?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
CYAN CEVI
  • 813
  • 1
  • 9
  • 19
  • I can't understand " suppose value "classVar" "is in another string variable".Can you explain what yop want. – P S M Mar 31 '16 at 12:20
  • What are you trying to do? – Abdelhak Mar 31 '16 at 12:20
  • end goal is to call classVar using object, but not directly. as in name of the class' variable is in another string variable var2. then how to call the classVar using var2 ? – CYAN CEVI Mar 31 '16 at 12:23

3 Answers3

2

Variable names are statically typed in Java. You cannot made them dynamically like this. You can use reflection, if you really need it.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You can use Reflections to get it.

Foo bin = new Foo();    

Now, Foo has a variable "classVar".

So, you do:

Field f1[] = Foo.class.getDeclaredFields();
for(Field f:f1)
{
     if(f.getName().equals("classVar"))
         System.out.println(f.get(bin)); //Get the value
}
dryairship
  • 6,022
  • 4
  • 28
  • 54
0

You can achieve that by using Reflection with just one line of code in a try-catch block, like below:

try {
        var2 = (String) bin.getClass().getField("classVar").get(bin);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

P.S. Using reflection generally can be risky if not controlled well. But it will amazingly increase your coding flexibility, if it is handled carefully.

Raptor
  • 187
  • 1
  • 2
  • 11