views:

42

answers:

3

Hi,

I have a custom class say class A :

class A
{
     public testA:int;
     public testB:int;

}

Now, I have a object say Object C , the object has the exact same names of variables and everything as the class.

My question can I cast that object into class or vice versa. Instead of set/get of individual variables.

+1  A: 

You can try reflection. See this article.

Bozho
Since, I'm using AMFPHP I think reflection is the way to go. Though I don't understand it completely yet :)
Fahim Akhter
A: 

No you cannot cast an Object into a Class, but since a Class is an Object you can do the other way, but remember that accessing member from a Class is faster that accessing member from an Object.

To transform an Object into a Class you will have to instanciate the Class and then copy each Object field into that Class. But beware they will not be the same instance it's a copy.

To make the reverse you will have to use describeType on the Class to enumerate all the public field of that Class, and then copy the value into a new Object.

// simple sample:
class A {
 public var testA:int;
 public var testB:int;
}

function Object2A(o:Object):A {
 var ret:A = new A();
 for (var fieldName:String in o) {
   if (ret.hasOwnProperty(fieldName)) {
    ret[fieldName] = o[fieldName];
   }
 }
 return ret;
}

import flash.utils.describeType;

function A2Object(a:A):Object {
 var ret:Object = {};
 var fields:XMLList=describeType(a).variable;
 for each(var field:XML in fields) {
  var fieldName:[email protected]();
  ret[fieldName]=a[fieldName];
 }
 return ret;
}

var o:Object = {testA:12, testB:13};

var a:A = Object2A(o); // copy from object into class

o=A2Object(a); // copy from class into object
Patrick
Basically, I'm trying not to individually set the class items. Asked the question, to know if there is a way of escaping that :) Thanks for the help though.
Fahim Akhter
A: 

Unfortunately, no. The rules of duck-typing (if it looks like a duck and quacks like a duck, then it must be a duck) do not apply in AS3. Unless an object is explicitly constructed as type A, then a classification test will fail when compared to a generic object with the same properties. To cast generics into typed objects, I've always done this:

var obj = ((your generic object))
var a:A = new A();

for (var prop in obj) {
   if (a.hasOwnProperty(prop)) a[prop] = obj[prop];
}
Greg