Nitish Gadangi
Nitish Gadangi

Reputation: 27

Is it possible to access a variable, using a string which holds that variables name in JAVA?

In Java, If I had a String already declared and it holds the name of a variable. Can I use that String to access that variable? For Example

int sample=10;
String test = "sample";

Here,is it possible use the string test to access integer variable sample. If yes, then how.

Upvotes: 1

Views: 114

Answers (1)

Chris Maggiulli
Chris Maggiulli

Reputation: 3814

Reflection

One of the strongest aspects of Java is the robust reflection API provided by the standard libraries.

Reflection allows you examine and modify the structures and behaviour of classes, methods, and attributes at runtime.

Reflection is, in my opinion, single handedly responsive for the robust Java ecosystem of platforms, frameworks, and JVM languages available today.

Caution

While reflection is powerful and is definitely a part of Java widespread success I caution against using it in many circumstances.

For the most part reflection is used in software used by other software (frameworks, platforms, languages, etc). Generally when I see someone ask about reflection (especially if they do not call it by name) they are thinking about the problem wrong.

I would definitely like to hear your use case so we can possibly suggest a different way of looking at it.

Sample Code

Below is some psuedo code that illustrates one way to accomplish what you are trying to do. I call it psuedo code because I have not compiled it, and it could likely be optimized.

Before adding it to your project I would like to reiterate that you should post your specific problem so we can analyze it and possibly help you think about it differently.

final String ATTR = "test";
Class<?> clazz = Class.forName("your.fully.qualified.class.name");     
Field[] fields = clazz.getFields();

for ( Field field : fields ) {
    String name = field.getName();

    if ( name == ATTR ) {
       Object value = field.get(name);
   }
}

Upvotes: 1

Related Questions