Can I access a Class attribute by its name?
for example:
class Test {
Integer GoodVar;
Integer BadVar;
...
void Func(String name, Integer value) {
// Set A Value based on its name
}
void Init() {
Func("GoodVar", 2);
Func("BadVar", 1);
}
}
can somebody code Func function?
You can use a switch statement, in JDK 7 the strings are allowed (see: http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html). Something like:
Pre JDK 7 you can use if statements instead.
Another approach it would be to use reflection (see: http://docs.oracle.com/javase/tutorial/reflect/index.html), but it’s slow, like: