Can I get parent class name ( first one) on inherit classes?

Viewed 177

At example I have three classes : View , FView ( extends View) and MView (extends View) . I have variable from type MView and want to to check it against parent class View ( i.e if this variable is from class View ). Is it possible to get the parent class ( View class) ? . Here is full example: https://try.haxe.org/#eA594

class Test {
    static function main() {
        var v = new SView();
        trace(Type.getClassName( Type.getSuperClass(Type.getClass(v))) );
    }
}

class View :

class View {
    public function new() {

    }
}

class FView :

class FView  extends View { 
    public function new() {
        super();
    }
}

class SView :

class SView  extends FView {
    public function new() {
        super();
    }
}
1 Answers

If you want to get to the base class, you can simply recurse or iterate until Type.getSuperClass() returns null:

// at runtime: find out what is the base class of `v`
var base:Class<Dynamic> = Type.getClass(v);
while (true) {
    var s = Type.getSuperClass(base);
    if (s == null)
        break;
    base = s;
}
trace(Type.getClassName(base));

However, you mention that you want to do this simply to check if MView (or SView) are of the View type.

Well, for this, there are a few simpler alternatives...

First, at compile type, you can simply use a type check (or an assignment) to check if v:SView unifies with View:

// at compile time: enforce that `v` be of type `View` or compatible with it
var v1 = (v:View);  // use a type check
var v2:View = v;    // or simply pass it to something expecting `View`

If you need to do it at runtime, that's possible as well with Std.is():

// at runtime: check if `v` is a subclass instance of `View`
trace(Std.is(v, View));

For a complete example, check out this Try Haxe instance.

Related