0

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".

Bluefire
  • 13,519
  • 24
  • 74
  • 118
  • What do you mean ? Do you want to pass by reference ? Your question is ununderstandable ... – aleroot Sep 11 '12 at 10:17
  • 2
    A possible duplicate [how to get the name of variable](http://stackoverflow.com/questions/744226/java-reflection-how-to-get-the-name-of-a-variable) – Aravind.HU Sep 11 '12 at 10:18
  • I feel I understand what you mean, but you should provide a better example - maybe just in pseudo code? – home Sep 11 '12 at 10:18

1 Answers1

4

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.

References:

João Silva
  • 89,303
  • 29
  • 152
  • 158
  • How would I get that to work if I wanted to define the name of a class as well as the name of a variable? So if I wrote `myMethod(someClass, someVariable)`, I would receive the value of `someClass.someVariable`. – Bluefire Sep 11 '12 at 15:38
  • Hang on a second - would this work for the above: `String path = someClass + "." + someVariable;` `String s = myMethod(path)` – Bluefire Sep 11 '12 at 15:41
  • @Bluefire: No, It's a bit more complicated. But I'm not sure if I understood you correctly. Say, for example, you have two instances of the class `Foo`, if you pass the className `Foo`, which of those instances would you choose? Also, it's probably better for you to open a new question for this. – João Silva Sep 11 '12 at 15:44