Search code examples
oophaxe

How to check whether an object is a descendant of a given class in Haxe?


I would like to be able to check whether an object is a descendant of a given class, but it does not seem possible.

I would like to port the following code from C#:

public virtual Systems Add(ISystem system) {
    var initializeSystem = system as IInitializeSystem;
    if(initializeSystem != null) {
        _initializeSystems.Add(initializeSystem);
    }

    var executeSystem = system as IExecuteSystem;
    if(executeSystem != null) {
        _executeSystems.Add(executeSystem);
    }

    var cleanupSystem = system as ICleanupSystem;
    if(cleanupSystem != null) {
        _cleanupSystems.Add(cleanupSystem);
    }

    var tearDownSystem = system as ITearDownSystem;
    if(tearDownSystem != null) {
        _tearDownSystems.Add(tearDownSystem);
    }

    return this;
}

What would be the best way to achieve the same functionality in Haxe? Note, that an object might be descendant of several classes I am testing for.


Solution

  • Have you tried Std.is()?

    if (Std.is(system, IInitializeSystem)) {
        _initializeSystems.add(cast system);
    }
    
    if (Std.is(system, IExecuteSystem)) {
        _executeSystems.add(cast system);
    }
    
    // etc