Is it possible to use Class<T> as a way to replace classes that get constructed?

I’m working on a toolset/haxelib and I want to provide easy ways for my users to override existing behaviors, and while I understand that inheritance offers the override keyword, I don’t want to make my users override my whole library just to change one class type and it’s behavior. As a loose example:

public static var MY_CLASS:Class<MyParentClass>;

function makeNewClass() {
   return Type.createInstance(MY_CLASS, []);
}

function replaceClass() {
   MY_CLASS = Class<MyChildClass>;
}

I want to be able to set MY_CLASS to the child/custom class the users would want to use. I understand that this is very likely not the correct way to use this, and whenever I have tried to use this Type.createInstance() has returned null every time and I’m not sure what I’m doing wrong. Any help for this would be appreciated, thank you for your time!

I would strongly suggest using constructor references for this instead, which avoids the unnecessary reflection / dynamic typing (no issues with DCE etc):

public static var makeNewClass:() -> MyParentClass = MyParentClass.new;

function replaceClass() {
   makeNewClass = MyChildClass.new;
}

…and then just call makeNewClass() like a normal function.

Nice blog post on this topic: CodingTips.new - Haxe - The Cross-platform Toolkit


As for why Type.createInstance() might be returning null… If you do it like in your code snippet there, MY_CLASS might not be initialized if replaceClass isn’t called? Also, should be MY_CLASS = MyChildClass.

1 Like

This worked as expected, thank you very much!