Reputation: 14109
I need to make a method that takes the name of a variable as its input, searches the class, and outputs the value pointed to by that variable. However, as you might have guessed, I am having problems with it:
public String myMethod(String varname) {
return varname;
}
As you can see, all the above does is return the input string. Is there any way to get it to do otherwise?
Edit: for those requesting an explanation, here it is:
Suppose I have the following code:
String foo = "foo";
String bar = "bar";
I want to make a method that takes the name of a variable and returns its value. So, if I used the above method and wrote myMethod(foo)
, the output would be "foo"; similarly, I want myMethod(bar)
to give "bar".
Upvotes: 0
Views: 403
Reputation: 91309
Use the Java Reflection API. For example:
private String foo = "foo text";
private String bar = "some text";
public String myMethod(String varname) throws Exception {
Class<?> c = this.getClass();
Field field = c.getDeclaredField(varname);
Object fieldValue = field.get(this);
return fieldValue.toString();
}
// myMethod("foo") returns "foo text"
// myMethod("bar") returns "some text"
DEMO.
Upvotes: 4