4

I've got a string which, in run-time, contains the name of a class that I want to instantiate. How would I do that?

I read suggestions to use flash.utils.getDefinitionByName():

var myClass:Class = getDefinitionByName("package.className") as Class;
var myInstance:* = new myClass();

However, that gives me the following error:

[Fault] exception, information=ReferenceError: Error #1065: Variable className is not defined.

Andy
  • 95
  • 1
  • 7
  • 2
    Your class still has to be defined elsewhere in order for Flash to get the definition, because all it does is check the current application domain. This is something I've struggled with and given up on before now. – shanethehat Aug 03 '11 at 22:51

2 Answers2

6

The easiest method I've come up with is to simply write the classnames out, separated by semicolons, anywhere in your project.

e.g. I create an Assets.as file with this in it:

package {   

public class Assets {       

    // To avoid errors from the compiler when calling getDefinitionByName
    // just list all of the classes that are not otherwise referenced in code:
    Balloon;
    Cloud;
    FlyingHorse;
    FlyingPig;
    UFO;
    Zeppelin;       
}
}

Full code example/tutorial on this is here: http://producerism.com/blog/flashpunk-dame-and-lua-tutorial-part-6/

producerism
  • 344
  • 4
  • 17
  • Thank you! This solved the problem. I thought it would be enough to `import` the class -- are imported classes not really imported if the compiler finds it unnecessary? – Andy Aug 04 '11 at 09:28
  • 1
    Correct - just because you import the class, doesn't mean it's actually compiled when you publish. Flash checks for the usage of each class, and only compiles the ones it finds in the actual code. That's why you can do import flash.display.* without affecting your filesize. – producerism Aug 04 '11 at 11:30
1

The other option is to use the mxmlc -includes compiler argument like this:

-includes=com.mydomain.package.MyClass

http://blogs.adobe.com/cantrell/archives/2010/09/loading-classes-dynamically-in-actionscript-3.html

René Höhle
  • 26,716
  • 22
  • 73
  • 82
Gab
  • 51
  • 1
  • 5