简体   繁体   中英

How to access a class variable by passing value to object from another variable?

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?

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

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
}

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();
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM