Got a class with a method that takes an object and loops through it, assigning the values of the object to the class. This can happen quite a bit in the application and I was wondering if there is an efficient and preferably language agnostic syntax to validate the property name of the object exists and confirm the value type before assigning to the class? I'm going to need to export this code to at least flash and javascript, possibly others to follow later. I need to keep the method generic because it lives in a base class. Something along the lines below:
public function updateProperties(propsObj:Object):void {
for (var prop in propsObj) {
if (/* this has prop && typeof propsObj[prop] == typeof this[prop] */) {
this[prop] = propsObj[prop];
}
}
}
New to Haxe, so I'm having some trouble finding the family of methods for this kind of thing. Reflect seems to have methods close to what I'm looking for, but a lot of the methods look like they may be overkill for what I need, was hoping for some insight.
This seems to work.
public function updateProperties(props:Dynamic) {
for (prop in Reflect.fields(props)) {
if (Reflect.hasField(this, prop)) {
Reflect.setProperty(this, prop, Reflect.getProperty(props, prop));
} else {
trace("cannot set property " + prop + " on " + this);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With