Java String value as part of statement?

102 Views Asked by At

I have a class declared to hold information. Let's say it has these fields

class data {
   int a;
   int b;
   int c;
}

And I want to access these fields like this:

String [] fields = {"a", "b", "c"};
data da = new data();
for (int i = 0; i < 3; i++) 
   if (da.fields[i] < 10)
      dosomething();

Is there any way in Java to do this? Googling, I got some results about something called "reflection, " but I've never really heard of that, and I don't think it's quite what I want. Is there any way to do this in Java? If not, are there any languages that support this kind of thing (just out of curiosity)?

4

There are 4 best solutions below

1
Karthik T On BEST ANSWER

Reflection is probably what you need. But what you need more is a hard look at your design. You should avoid reflection where possible.

If you are still interested in doing this, take a look at Java Reflection: Fields.

Field field = aClass.getField("someField");

Is what you would do to get the field by that name. A more detailed example of what you want.

Class  aClass = MyObject.class
Field field = aClass.getField("someField");

MyObject objectInstance = new MyObject();

Object value = field.get(objectInstance);

field.set(objetInstance, value);
0
Trasvi On

Reflection is the way to go. Karthik T has the correct answer. Without using reflection:

Declare the fields to be an array (or a Map), and the names as lookups:

class data {
    int[] fields = new int[3];
    public static final int A = 0;
    public static final int B = 1;
    public static final int C = 2;
 }

 public void foo() {
     data da = new data();
    int[] fields = {data.A, data.B, data.C};
    for (int n : fields) {
       if (da.fields[n] < 10) doSomething();
    }
 }

Its ugly, and your design is probably wrong if you want to do something like this, but it works.

0
Bohemian On

You could add a suitable API to your class:

class data {
   int a;
   int b;
   int c;

   int get(String field) {
       if (field.equals("a")) return a;
       if (field.equals("b")) return b;
       if (field.equals("c")) return c;
       throw new IllegalArgumentException();
   }
}

Then you could:

String [] fields = {"a", "b", "c"};
data da = new data();
for (int i = 0; i < 3; i++) 
   if (da.get(fields[i]) < 10)
      dosomething();
0
SylvainL On

You don't really say what's your real problem; so it's hard to say if using reflection or something else is what you need. However, when someone talk about associating a string value with another variable, what they often need to use is a Map (or a dictionary in other languages); something along the line of:

    TreeMap<String, Integer> tm = new TreeMap<String, Integer>();       
    tm.put("a", 1);
    tm.put("b", 2);
    tm.put("c", 3);

    for (String k: tm.keySet()) {
        System.out.println(k + ": " + tm.get(k));
    }