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")?

1
  • Ah, I see what you mean now. I've updated my answer below. Commented Jan 19, 2009 at 21:30

2 Answers 2

6

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. :)

Sign up to request clarification or add additional context in comments.

Comments

4

"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"

1 Comment

Nice -- I didn't know it could be referenced as Foo["bar"] as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.