views:

764

answers:

2

Let's say that I have a class Foo:

public class Foo
{

   public static var bar:String = "test";

}

How can I reference bar at runtime using the string "Foo" or/and and instance of Foo and the string "bar"?

I.e.

var x:Object = new Foo();
...
x["bar"]

...doesn't work, debug mode in IntelliJ got my hopesup as bar gets listed as a property.

Update:

Note that at the "point of action" I don't know anything about foo in compile time. I need to resolve Foo.bar through the strings "Foo" and "bar".

Of put differently, as flex don't have eval how can I accomplishe the same as eval("Foo.bar")?

+4  A: 

It's a static variable, so you won't be able to access it using an instance of foo; it's accessed statically, using ClassName.variableName notation, like so:

trace(Foo.bar);

// yields: "test"

As well, because you've declared both Foo and bar public, you should be able to access Foo.bar that way from anywhere in your application.


Update: Ah, I see what you're asking. You can use flash.utils.Summary.getDefinitionByName():

// Either this way
trace(getDefinitionByName("Foo").bar);

// Or this
trace(getDefinitionByName("Foo")["bar"]);

... the latter thanks to Jeremy's answer, which was new to me. :)

Christian Nunciato
+3  A: 

"bar" is a static variable, so you need to access it through the class instead of an instance of the class.

trace(Foo.bar); // "test"

If by dynamically accessing the variable, you mean accessing it with a string name, then you want to do that through the class as well.

trace(Foo["bar"]); // "test"
Jeremy
Nice -- I didn't know it could be referenced as Foo["bar"] as well.
Christian Nunciato