I'm trying to pass a Class reference and instantiate it in a function. This doesn't work:
function foo(myClassRef:Class):Void {
var myVar = new myClassRef();
}
foo(MyClass);
It gives Unexpected (
.
Is this possible in Haxe 3?
To do this, either we can use Object. clone() method or define a constructor that takes an object of its class as a parameter.
Introduction to Class ParametersA class parameter defines a special constant value available to all objects of a given class. When you create a class definition (or at any point before compilation), you can set the values for its class parameters.
yes of coarse you can pass classes or functions or even modules ... def foo(): pass here it gives it address for ex. function foo at0x024E4463 means it is given address of foo function but in class itdoesnt means class foo: pass here it gives <class.
In Java, we can pass a reference to an object (also called a "handle")as a parameter. We can then change something inside the object; we just can't change what object the handle refers to.
Class has a Type Parameter, so if you're going to accept 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 sub classes:
function foo(myClassRef:Class<sys.db.Object>):Void {
var myVar = Type.createInstance( myClassRef, [] );
trace( Type.typeof(myVar) );
}
Haxe 3 also allows generic functions:
@:generic function foo<T:Dynamic>(t:Class<T>) {
var myVar = new T();
trace( Type.typeof(myVar) );
}
Here you declare the function to be generic, which means that for each different type parameter, a different version of the function will be compiled. You accept Class, where T is the type parameter - in this case, dynamic, so it will work with any class. Finally, using generic functions let's you write new T()
, which may seem a more natural syntax, and there may be performance benefits on some platforms.
It is possible in Haxe3 and Haxe2
function foo<T>(myClassRef:T):Void {
var myVar = new T();
}
Note: Haxe3 class (where foo is implemented) must be @:generic if you want new T() to work.
Haxe2 is another story:
function foo<T>(myClassRef:Class<T>):Void {
var myVar = Type.createEmptyInstance(Type.getClass(myClassRef));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With