Reputation: 609
I would like to dynamically invoke a Class
's Property
via a String
. In the following code, I can dynamically invoke a Class
's Function
via a String
.
var myClass:Class = getDefinitionByName("myPackage.MyClass") as Class;
myClass["myStaticMethod"]();
where MyClass
is defined as:
package myPackage {
public class MyClass {
public function MyClass() {}
public function myMethod():void {};
public static function myStaticMethod():void {};
public static function get myProperty():Object { return null; }
}
}
However, a Property
, such as MyClass.myProperty
is not a Function
. So,
var myClass:Class = getDefinitionByName("myPackage.MyClass") as Class;
myClass["myProperty"]();
throws an error: TypeError: Error #1006: value is not a function
because myProperty
is not a Function
.
Is there any way to do this dynamically via String
s?
Thanks for the help.
Upvotes: 1
Views: 195
Reputation: 491
The Answer of Alex will indeed works properly, but only if you have the String written properly. Else you get this error thrown at you: TypeError: Error #1006: value is not a function.
To avoid this you could try test if the property or method is defined before using it. Like so:
if(myClass["myProperty"] != undefined)
{
...
}
Anyhow, in your specific example you are requesting a getter, and that's why you had to remove the ()
from your source. If you would be needing a method, I would also recommend you to save the method as a function:
var myFunction: Function = myClass["theFunction"];
And then to use either the call
or the apply
methods.
myFunction.call(null, myParam);
IF you are interested in studying all the methods that an Object has and comparing them to a String. Consider also:
var child:Sprite = new Sprite();
var description:XML = describeType(child);
var methodList: XMLList = description.descendants('method');
The attributes of a <method/>
node are:
I hope this helps out, let me know if you found it useful.
Upvotes: 2
Reputation: 609
To solve this issue, I simply needed to remove the ()
from the code. That is, the new code looks like:
var myClass:Class = getDefinitionByName("myPackage.MyClass") as Class;
myClass["myProperty"]; // This works.
Upvotes: 2