AS3: call a static class method - class and method names are strings
actionscript-3, apache-flex, flash
Solution
The reason is that the compiler will strip out unnecessary classes - if you don't have an explicit reference to the class `Foo` somewhere, it won't be present in your final application.
You could the reference elsewhere and still force it to be loaded - for example, a static array of references to the classes.
Problem
I have an ugly problem. I have two string variables (className and staticMethod) store the name of a class and it's static method I have to call: ``` package { import flash.display.Sprite; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; public class ClassPlay extends Sprite { public function ClassPlay() { new Foo(); var className:String = 'Foo'; var staticMethod:String = 'bar'; var classClass:Class = getDefinitionByName(className) as Class; try { classClass[staticMethod](); } catch (e:Error) {} } } } ``` This is the subject class: ``` package { public class Foo { public static function bar():void {trace('Foo.bar() was called.');} } } ``` It works just perfectly. The problem when you comment out this (9th) line: ``` // new Foo(); ``` Without this line it exits with an exception: ``` ReferenceError: Error #1065: Variable Foo is not defined. ``` How could I do this without that instantiation? If that is impossible, is there a way to instantiate the class from the string variable? Or if it's still a bad practice, how would you do that? (I have to work with those two unknown string variable.) Thanks in advance.