In AS3 I can write this["foo"] for acces to varible foo. I can construct any string in brackets. Is there a way to do this in Java?
+3
A:
You can use Java's reflection API to achieve the same effect, albeit much less elegantly. See here for a tutorial.
Marcelo Cantos
2010-05-01 22:15:34
Not to mention slower and potentially insecure.
Longpoke
2010-05-01 22:18:09
Slower than ActionScript's this["foo"]? Perhaps, but I'd say there's sufficient uncertainty to warrant measuring the difference.
Marcelo Cantos
2010-05-01 23:15:53
A:
No. If you want such kind of access, you should consider using Set interface (or reflection api, as noted before me).
Nikita Rybak
2010-05-01 22:16:03
+1
A:
No, you can't do this. But you don't need to. There's an easier way to call variables. You just need to use this.foo to refer to the variable. Now, if you're trying to do something like
String var = "foo";
this[var] = "something else";
You may be able to do that with java reflection, but it would have quite a bit of overhead and I believe it would be quite inefficient.
Brent Parker
2010-05-01 22:17:15