Search code examples
haxe

Is there a way of getting the names of all subclasses


I want to get the names of all subclasses of a base class. From that I want to @:build an enum where every entry is the name of a class. Is this possible?


Solution

  • Here is the code. The order of macro executions is undefined, as specified in documentation.

    [AutoBuildingMacro.hx]

    import haxe.macro.Context;
    import haxe.macro.Expr;
    
    final mapofnames = new Map<String,Array<String>>();
    
    class AutoBuildingMacro {
      public static macro function fromBaseClass(base):Array<Field> {
        var parent = haxe.macro.ExprTools.toString(base);
        var names = mapofnames[parent];
        if ( names == null ) {
          names = new Array<String>();
          mapofnames[parent] = names;
        }
        names.push(Context.getLocalClass().toString());
        trace(mapofnames);
        return null;
      }
    }
    

    [Main.hx]

    import AutoBuildingMacro;
    
    class Main {
      static public function main() {}
    }
    
    @:autoBuild(AutoBuildingMacro.fromBaseClass(Parent))
    class Parent {
    }
    
    class Child1 extends Parent {
    }
    
    class Child2 extends Parent {
    }
    
    class Child3 extends Child2 {
    }
    

    Output:

    AutoBuildingMacro.hx:15: {Parent => [Child2]}

    AutoBuildingMacro.hx:15: {Parent => [Child2,Child3]}

    AutoBuildingMacro.hx:15: {Parent => [Child2,Child3,Child1]}