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)?
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);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With