Pass class as parameter

I am trying to pass a reference to a class and create an instance in a function. This does not work:

function foo(myClassRef:Class):Void { var myVar = new myClassRef(); } foo(MyClass); 

It gives Unexpected ( .

Is this possible in Haxe 3?

+7
haxe
source share
2 answers

Class has a type parameter , so if you are going to take a class as an argument, you need to specify a type parameter.

Accept any class:

 function foo(myClassRef:Class<Dynamic>):Void { var myVar = Type.createInstance( myClassRef, [constructorArg1, constructorArg2....] ); trace( Type.typeof(myVar) ); } 

Accept only sys.db.Object class or subclasses:

 function foo(myClassRef:Class<sys.db.Object>):Void { var myVar = Type.createInstance( myClassRef, [] ); trace( Type.typeof(myVar) ); } 

Haxe 3 also allows common features :

 @:generic function foo<T:Dynamic>(t:Class<T>) { var myVar = new T(); trace( Type.typeof(myVar) ); } 

Here you declare the function common, which means that for each parameter of a different type, a different version of the function will be compiled. You accept a Class, where T is a type parameter - in this case - dynamic, so it will work with any class. Finally, using common functions, you can write new T() , which may seem like a more natural syntax, and on some platforms there may be performance benefits.

+11
source share

It is possible in Haxe3 and Haxe2

 function foo<T>(myClassRef:T):Void { var myVar = new T(); 

}

Note. The Haxe3 class (where foo is implemented) should be @: generic if you want the new T () to work.

Haxe2 is another story:

 function foo<T>(myClassRef:Class<T>):Void { var myVar = Type.createEmptyInstance(Type.getClass(myClassRef)); 

}

+4
source share

All Articles