Search code examples
reflectiontypesinstantiationhaxe

How to create an instance from string name?


Similar to this question, but I'm looking for a Haxe 3.0 solution. I'm looking to instantiate a class based on a a string (from my data file).

As far as I can tell this is correct. However, I get a runtime error

[Fault] exception, information=No such constructor npc.NPC_Squid
Fault, createEnum() at Type.hx:166

The Haxe 3 Code:

var e = haxe.macro.Expr.ExprDef;            
var instance :Dynamic = e.createByName( "npc." +  data.character, [] );
    //....

My class:

package npc;

import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;
import openfl.Assets;

class NPC_Squid extends Sprite
{   
    public function new()
    {
        super();
        addEventListener( Event.ADDED_TO_STAGE, onAdded);
        addEventListener( Event.REMOVED_FROM_STAGE, onRemoved);

    }
//....

My packages seem correct. Any ideas as to why it can't find the constructor?


Solution

  • I think you would need this:

     var myInstance = Type.createInstance(Type.resolveClass("mypackage.MyClass"));
    

    Note if you use dead-code elimination, you should import/reference MyClass somewhere. I mostly create a function forceCompile in my Main class for such things:

     public static function main() 
     {
        forceCompile();
    
        // Wind up all your stuff
     }
    
     public static function forceCompile()
     {
          MyClass;
     }