How to check if a property is in a class?


#1

Hello,

how to check if a property is in a class ?

var test:Bool = true;

if “test” exist ?
I tried

Reflect.hasField( this, "test" )

but it return allways false

Thanks


#2

hasField is for checking anonymous types, like so

trace(Reflect.hasField({{bar:0}}, "bar"));  //true

For typed classes you should determine the type and cast it to access those properties.

class Test {
    static function main() {
        var thing:Dynamic = new Foo();
        
        if (Std.is(thing, Foo)) {
            
            var foo:Foo = cast thing;
            trace(foo.bar);
        }
    }
}
class Foo {
    public var bar:Int = 0;
    public function new (){}
}

if you have a bunch on classes that may have a property or method you should use an interface


#3

Try Reflect.hasField(this, "test") instead.

If that doesn’t work, use Type.getClassFields(Type.getClass(this)) or Type.getInstanceFields(Type.getClass(this)).

If that doesn’t work, check the superclasses:

function hasFieldNamed(object:Dynamic, fieldName:String):Bool {
    var c:Class<Dynamic> = Type.getClass(object);
    while(c != null) {
        if(Type.getInstanceFields(c).indexOf(fieldName) >= 0
            || Type.getClassFields(c).indexOf(fieldName) >= 0) {
            return true;
        }
        
        c = Type.getSuperClass(c);
    }
    
    return false;
}

That said, it’s generally better to use an interface where possible:

interface TestBool {
    public var test:Bool;
}

class MyClass implements TestBool {
    public var test:Bool;
    
    public function new() {
        test = Math.random() < 0.5;
        trace(MyOtherClass.getTestResult(this));
    }
}

class MyOtherClass {
    public static function getTestResult(testObject:Dynamic):Bool {
        if(Std.is(testObject, TestBool)) {
            return (cast testObject:TestBool).test;
        } else {
            return false;
        }
    }
}

…or at least a typedef:

typedef TestBool = {
    var test:Bool;
}

class MyClass {
    public var test:Bool;
    
    public function new() {
        test = Math.random() < 0.5;
        trace(MyOtherClass.getTestResult(this));
    }
}

class MyOtherClass {
    public static function getTestResult(testObject:TestBool):Bool {
        return testObject.test;
    }
}

#4
Reflect.hasField( this, "test" );

work if I use

Reflect.setProperty( this, "test", true );