haXe Forum > Check a Dynamic's type or castabil

  • I'm a bit confused by the documentation relating to RTTI. Is there a way to check if a Dynamic variable contains a value of type X (*or* a type that inherits X)? For instance:

    class Base {}
    class Derived extends Base {}
    void Foo(x:Dynamic):Void
    {
        if( /* x is a String */ )
            trace("A");
        else if( /* x is a Base (or anything inherited from Base) */ )
            trace("B");
        else  // Something else
            trace("C");
    }
    
    Foo("hello"); // A
    Foo(new Base()); // B
    Foo(new Derived()); // B
    Foo(new Object()); // C
    Foo(7); // C

    If there's a way to do that without trying to cast(,) it and catching 'bad cast' exceptions: How? If not, how can I make a utility function like this work?:

    // Psuedo-code:
    public static function isCastableTo(var, type):Bool
    {
        try
        {
            var tmp = cast(var, type);
        }
        catch(e:Dynamic)
        {
            return false;
        }
        return true;
    }

  • There you get all interfaces and the superclass for a class using RTTI Classdef. This works only if the classes are compiled with RTTI (Runtime Type Informations).
    For all other cases take a look at Type, there is a getClassName function, but this gives you no informations about the superclasses.
    For the most basic types you could work with Std.is().

  • Thanks. Std.is() is exactly what I was looking for. I guess I overlooked it cause I was looking in Type and Reflect.

< Prev | Page 1 / 1 | Next >