This is essentially impossible. And this has nothing to do with ActionScript. In most other languages โโyou have the same problem, since on the left side you have an anonymous object if the language supports any such thing or hash. Anyway. There are different solutions, this will be one that can handle several things:
package { public class ObjectUtils { public static function createInstance(constructor:Class):* { var ret:*; switch (describeType(to).factory.constructor.parameter.(@optional == "false").length()) { case 0: ret = new to(); break; case 1: ret = new to(null); break; case 2: ret = new to(null, null); break; case 3: ret = new to(null, null, null); break; case 4: ret = new to(null, null, null, null); break; case 5: ret = new to(null, null, null, null, null); break; case 6: ret = new to(null, null, null, null, null, null); break; case 7: ret = new to(null, null, null, null, null, null, null); break; case 8: ret = new to(null, null, null, null, null, null, null, null); break; case 9: ret = new to(null, null, null, null, null, null, null, null, null); break; default: throw new Error("no implementation for instantiating classes that require more than 9 constructor arguments"); } return ret; } public static function castAnonymous(obj:Object, to:Class):* { var ret = createInstance(obj); for (var name:String in obj) try { ret[name] = obj[name]; } catch (e:Error) { throw new Error("error trying to assign value " + obj[name] + " to property " + name + " on " + ret + ". reason: " + e); } return ret; } } }
limitations:
- will fail if your panic class, if it is spam with zeros when building, or the constructor needs more than 9 arguments
- fails, and also cannot recursively, so it can simply assign anonymous objects or arrays to the properties of the returned instance
hope this helps anyway;)
Greetz
back2dos
back2dos
source share