Create an instance of a class from a string name in Haxe
Asked Answered
T

1

8

Let's say i acquire the name of a class that i made as a String. How can i Instantiate the class with the name contained in that string? I I know it will be derived from a certain parent class, but the actual class will vary.

Taw answered 8/9, 2010 at 9:56 Comment(0)
W
17
var instance : MyClass = Type.createInstance(Type.resolveClass("path.to.MyClass"), []);

Few notes:

  • resolveClass() takes the full path (packages included) of the classe you need
  • createInstance() takes as the second argument an array of values that are applied to the constructor. Those values must be in the exact number and must be passed even if they are optional (nulls are good in that case).
Wanigan answered 8/9, 2010 at 12:25 Comment(2)
But how can i know the name of "MyClass" for the instance dataType, when i got the name of the class from the string? For example: gist.github.com/danbruegge/d51a9d233b4944327be6 I create this class with a function. But how do i know the dataType for the variable instance?Voucher
@danbruegge, if you mean to type something at runtime, you just can't. Usually you want to have a common shared type you can rely upon, an interface, a base class or a typedef for example.Wanigan

© 2022 - 2024 — McMap. All rights reserved.