haXe Forum > Check a Dynamic's type or castabil
-
Nick Sabalausky Feb 24 at 02:13
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; }
-
Philipp Klose Feb 24 at 20:56
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 agetClassNamefunction, but this gives you no informations about the superclasses.
For the most basic types you could work withStd.is(). -
Nick Sabalausky Feb 26 at 00:29
Thanks. Std.is() is exactly what I was looking for. I guess I overlooked it cause I was looking in Type and Reflect.