views:

98

answers:

3

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
Not to mention slower and potentially insecure.
Longpoke
Slower than ActionScript's this["foo"]? Perhaps, but I'd say there's sufficient uncertainty to warrant measuring the difference.
Marcelo Cantos
A: 

No. If you want such kind of access, you should consider using Set interface (or reflection api, as noted before me).

Nikita Rybak
+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