1

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 Strings?

Thanks for the help.

2 Answers 2

2

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.
2
  • Not sure sure if you already figured this out or needed it but now what you'll have is a Class typed object in your array so you can call new myClass["myProperty"]() to create instances. Jul 31, 2012 at 19:10
  • 1
    @shaunhusain You mean new myClass(); Aug 1, 2012 at 7:58
2

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:

  • name: The name of the method.
  • declaredBy: The class that contains the method definition.
  • returnType: The data type of the method's return value.

I hope this helps out, let me know if you found it useful.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.