的Flex / ActionScript代码:动态访问静态无功静态、代码、动态、Flex

2023-09-08 13:51:48 作者:@掏粪男孩

让我们说,我有一个类Foo:

Let's say that I have a class Foo:

public class Foo
{

   public static var bar:String = "test";

}

使用字符串foo或/和和实例美孚和字符串bar我怎么可以参考一下吧在运行时?

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

即。

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

...不工作,在的IntelliJ调试模式下得到了我的hopesup,酒吧被列为一个属性。

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

更新:

请注意,在点行动我不知道FOO在编译的时候什么。我需要通过字符串富和栏,以解决Foo.bar。

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

放不同,如柔性没有的eval我怎么能accomplishe一样的eval(Foo.bar​​)?

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

推荐答案

这是一个静态变量,所以你将不能够使用的实例来访问它的FOO的;它的静态访问,使用ClassName.variableName符号,像这样:

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:

跟踪(Foo.bar);

trace(Foo.bar);

//收益:测试

为好,因为你已经声明为Foo和公示栏,你应该能够从任何地方访问Foo.bar这样在你的应用程序。

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.

更新:啊,我知道你在问什么。您可以使用flash.utils.Summary.getDefinitionByName():

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