Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check class for property and type

Tags:

haxe

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.

like image 740
Shane Avatar asked Jan 29 '26 01:01

Shane


1 Answers

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);
    }
  }
}
like image 130
Shane Avatar answered Jan 30 '26 16:01

Shane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!