Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Class as parameter

Tags:

haxe

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?

like image 991
Jorjon Avatar asked Aug 13 '13 19:08

Jorjon


People also ask

How do you pass a class object as a parameter in Java?

To do this, either we can use Object. clone() method or define a constructor that takes an object of its class as a parameter.

Can a class have parameters?

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.

Can a class is passed in function?

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.

Can I pass an object as a parameter Java?

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.


2 Answers

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.

like image 129
Jason O'Neil Avatar answered Sep 30 '22 19:09

Jason O'Neil


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));

}

like image 28
Vox Avatar answered Sep 30 '22 21:09

Vox