1

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?

Gama11
  • 31,714
  • 9
  • 78
  • 100
FlavorScape
  • 13,301
  • 12
  • 75
  • 117
  • Possible duplicate of [Create an instance of a class from a string name in Haxe](https://stackoverflow.com/questions/3666527/create-an-instance-of-a-class-from-a-string-name-in-haxe) – Gama11 Feb 03 '19 at 12:56

2 Answers2

1

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;
 }
Mark Knol
  • 9,663
  • 3
  • 29
  • 44
  • I tried the forced reference trick... no luck. Also, the Type.createInstance does not exist in HaXe 3.0. That's why i'm using the macro createByName(...); It looks like it is trying to resolve the constructor though (and not finding it). – FlavorScape Dec 05 '13 at 00:59
  • 2
    Type.createInstance() has not been removed in Haxe 3 and should work. Possible reasons for the constructor not to be found are DCE (in that case just add @:keep) or that the type is not imported anywhere in your project. – Franco Ponticelli Dec 05 '13 at 02:13
  • ooooooh. Haha, I had accidentally auto-imported haxe.macro.Type which is why it was saying these functions do not exist! – FlavorScape Dec 06 '13 at 20:01
1

In my Haxe 3 project, I use:

var easing: IEasing = Type.createEmptyInstance(Type.resolveClass("motion.easing." + easingType + easingStyle));

And it worked perfectly. One important precision: you need to import all the class that can be created this way. I imported all my motion.easing package to be sure.

You can see the full example here

NorTicUs
  • 718
  • 1
  • 10
  • 27