Silver
Silver

Reputation: 561

How to reference a variable using a string

I am attempting to reference a variable using a certain string but have no idea how to do it. I know that I can use if statements if I really had to but I am sure that there is a simple way. An example is a Integer named dog. I would try to access the Integer using another string that contained the text dog.

  private int dog;
    String anything = "dog";

Is there anyway this is possible? Thanks!

Upvotes: 2

Views: 210

Answers (4)

Elliott Frisch
Elliott Frisch

Reputation: 201447

You should use a Map of String to Integer. For example,

public static void main(String[] args) {
  java.util.Map<String, Integer> dogMap = new java.util.HashMap<String, Integer>();
  dogMap.put("Snoop", 10);
  dogMap.put("doggy", 15);
  dogMap.put("dog", 20);

  System.out.println(dogMap);
}

Which outputs

{doggy=15, Snoop=10, dog=20}

Upvotes: 0

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

Two options: create a Map<String, Object> that connects the two, or use reflection. I prefer reflection.

in order to get the field:

public class Test {
    private int dog = 10;
    private String anything = "dog";

    public static void main(String[] args){
        Test obj = new Test();
        Object field = obj.getClass()
                          .getDeclaredField(obj.anything)
                          .get(obj);            
        System.out.println(field);
    }
}

Output:

10

Create an object of the class that you will use. Then use the getDeclaredField() method on the class of that object. This will look into the private fields that are set, getField() holds only the public fields. That's it.

I've removed the try-catch from the post because it just clutters it.

Upvotes: -1

Floegipoky
Floegipoky

Reputation: 3273

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

public static void main(String[] args) {
    Map<String, MyObject> mapping = new HashMap<>();
}

Or new HashMap<String, MyObject>(); for pre java 7

Upvotes: 0

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

Try this:

// use a map for referring to a value given its name
Map<String, Integer> vars = new HashMap<String, Integer>();

// for example, let's use these values
String anything = "dog";
int dog = 10;

// bind a value to a name
vars.put(anything, dog);

// retrieve the value, given its name
vars.get(anything);
=> 10

Upvotes: 2

Related Questions