Cast an Object

0
August 17, 2011

Im having trouble casting.   Heres what Ive got....

in my first frame...

var blah:myClass = new myClass();

var obj:Object = new Object();

obj.m_id = "1234-ABCD";

blah = myClass(obj);    //   <-------casting here

trace(blah);                 //   <-------blah is null because the cast didnt work

Then...in my myClass.AS file....

class myClass{

    private var m_id:String = null;

    /** Creates a new instance of myClass */

    public function myClass() {

      trace("myClass Constructor");

    }    

    public function setId( id:String ) {

       m_id = id;

    }

    public function getId() : String {

       return m_id;

    }

Comments See all(0)

Add comment
0
August 17, 2011

best off passing your init data around as a vanilla "object" until you're ready to do something with it. Remember that all of your classes will inherit any properties you set in the parent class "Object". To answer your question can't dynamically cast by doing new <obJectName>:<objectType>.

It looks like convenient shorthand but (imho) would cause more headaches than it would alleviate.

login_btn.onPress = function(){

      resObj = TestService.getSkill();

      resObj.onResult = function(res) {

            var classData:Object = loadClassData(res);

            var myObject;

            switch(classData.m_classNa

me){

                  case "Skill" : myObject = new Skill(classData);break;

                  case "Foo" : myObject = new Foo(classData);break;

            }

      }

}

0
August 17, 2011

I'm not sure what your trying to do......

>blah = myClass(obj);

myClass is the name of your class. You can't call any methods or class members without creating an instance of it

class myClass

{

    var m_id:String;    //Setting this var to private means only the class can access the string.....so you can't set or get the variable from outside the class

    //public   is set to functions and vars by default.....theres no need to use 'public' unless your using public and private instances

    function myClass(id:String)    //initiates the variable within the constructor function

    {

        this.m_id = id;   //sets the m_id to the argument value

        trace("myClass constructor");    //traces a string

        trace("my id string is " + this.m_id);   //traces a string with the variable

    }

}

To use the class.......

var blah:myClass = new myClass("ABCDEFG"); //sets a new instance of myClass and sets the variable

/*

Will output....

myClass constructor

my id string is ABCDEFG

*/

For this type of class, theres no need to use getID and set ID.

Cheers

-OBCT

0
August 17, 2011

Thanks for the quick response...

Actually I stripped down the code in order to test it.  Im having problems essentially with this...

I have an object (that was returned from a webservice call)

the object is popluated with a bunch of properties.

result -

      ID                    "1234ABCD"

      Description        "CastTest"

      m_id                 "1234ABCD"

      m_description    "CastTest"

etc...

I have a class (myClass) that I need to populate with 'result'.

Here's more of the actual code (not stripped down)

class myClass {

    private var m_id:String = null;

    private var m_view:View = null;

    private var m_description:String = null;

    private var m_layout:String = null;           

    private var m_presentation:Array = null;

    private var m_timeRequired:Number = 90;  // Time to display in seconds

    /** Creates a new instance of myClass */

    public function myClass() {

            trace("myClass constructor called");

    }    

    public function setId( id:String ) {

       m_id = id;

    }

    public function getId() : String {

       return m_id;

    }

    public function getTimeRequired() : Number {

       return m_timeRequired;

    }  

    public function setTimeRequired( tm:Number ) {

       m_timeRequired = tm;

    }      

    public function getDescription() : String {

       return m_description;  

    }

    public function setDescription( desc:String ) {

       m_description = desc;  

    }    

      public function getPresentation(): Array {

            return this.m_presentation;

      }

      public function setPresentation( pres:Array ) {

            this.m_presentation = pres;

      }      

      public function getLayout(): Array {

            return this.m_presentation;

      }

      public function setLayout( layout:String ) {

            this.m_layout = layout;

      }      

    public function toString() : String {

        return m_id;

    }  

}

THEN IN THE FIRST FRAME OF MY FLA....

login_btn.onPress = function(){

      var s:String = "address to webservice";

      var TestService = new mx.services.WebService(s);

      TestService.onLoad = trace("TestService Loaded...");

      resObj = TestService.getmyClass();  <--- call to webservice (returns an object);

      resObj.onResult = function(result){

            var blah:myClass = new myClass();

            //blah.getId();  //able to step into myClass.getId here. ( prior to assignment!!!)

            blah = myClass(result);   //<---- Cast here  (result is populated with all properties)

            trace(blah);      //blah is null (cast didnt work)

            //result.getId();  //doesnt work

            //trace(blah.getId());  //doesnt work

      }

}

All I need to do is CAST result to blah so I can say blah.getId and it will return a value.  Right now...if I call blah.getId() it never steps into the AS class code.   I get the 'myClass constructor called' trace statement when the 'var blah:myClass = new myClass(); is executed.

thanks so much for the help. :)

knoxxx

0
August 17, 2011

//blah.getId();  //able to step into myClass.getId here. ( prior to assignment!!!)

---> that's normal. Your constructor for myClass sets getId to null.

What you're trying to do is to populate myClass with values -- not "cast". Casting is changing the parent class of a variable. You need to change the constructor to something like this:

//////// START ////////

    public function myClass(res) {

          trace("myClass constructor called -- populating values");

          m_view:View = res.View;

          m_description:String = res.description;

          m_layout:String = res.layout;          

          m_presentation:Array = res.presentation;

          m_timeRequired:Number = res.timeRequired;

    }  

////////  END  ////////

now your call to populate it needs to look like this:

  resObj.onResult = function(result){

          var blah:myClass = myClass(result);  //<--- class created and populated with values from result

          //blah.getId();  

          trace(blah);    

          //result.getId();

          //trace(blah.getId());

}

NB -- when you are currently calling trace(blah) the reason it's showing "null" is because you have a toString method which is returning the ID (which is set to null initially)

0
August 17, 2011

ccarey....thanks for the insight.  I didnt think about adding logic to the constructor.  

I would rather do something like this...(if possible)

//Once my webservice call returns my object....I'd like to call a method that loops through and populates all of the class properties.

login_btn.onPress = function(){

                resObj = TestService.getSkill();

      resObj.onResult = function(res) {

            //I'd like to use this for loading all of my classes (how do I instantiate my class if I dont know which class Im creating..

      //Instead of 'var s:Skill'  I would need to do 'var:res.m_className      = loadClassData(res) -- Is this legal???

                var s:Skill = loadClassData(res);

}

then in loadClassData....

//Cant return 'Skill' here because I dont know which class.

function loadClassData(res:Object):

Skill {

               cant create 'skl' of type 'Skill' because I dont know which class....

      var skl:Skill = new Skill();

      for(obj in res){

                                                //This will trace all of my object (ie... result.description = "myDescr")

                  trace("result." + obj + " = " + res[obj]);

                  I need to add property get/set methods for each property.

                                                skl.addProperty(obj, get, set);  //Will this work????

                  var obj2:Object = res[obj];

                  //This will trace objects of objects

                  for(subobj in obj2){

                        trace("result." + obj + "." + subobj + " = " + obj2[subobj]);

                        var obj3:Object = obj2[subobj];

                        for(subsubobj in obj3){

                              trace("result." + obj + "." + subobj + "." + subsubobj + " = " + obj3[subsubobj]);

                        }

                  }

      }

      return skl;  

}

So......in a nutshell.....how do I create an instance of my class when i dont know what the class name is??  I dont think I can use variables.   If I pass the class name in the object returned (res) can I go like this.... var clsNm: res[m_className] ?????

thanks,

knoxx

Related Questions

Casting an object back to it's original type at runtime

I am just starting with C++ and managed Extensions and I&#39;m trying to figure out how to convert an object back to it&#39;s original type after a cast. If an object gets implicitly cast to another t Read More

Views

39

Votes

0

Answers

18

August 17, 2011

Problem in deserializing an Object over URLConnection , when Object is different on receiving side

Hi, &#160; &#160; &#160; &#160; I have application W deployed on WebLogic. This app W has one Java object JO which is serializable. I have application A on ATG. app W and app A are same except java ob Read More

Views

10

Votes

0

Answers

3

August 16, 2011

Object reference not set to an instance of an object

I am looking to populate a formview embedded within a repeater in my ASP.NET Page. I am fairly sure that I am on the right track but am falling over close to the end with &quot;Object reference not se Read More

Views

1

Votes

0

Answers

11

August 16, 2011

Various questions

True or false? If false, please let me know what is the ? Thanks. There is no private variables in classes. They can only be declared public. You can define a contructor but not a destructor in classe Read More

Views

8

Votes

0

Answers

8

August 16, 2011

ULTIMATE Smack Down ::>> Generics vs Casting

Hi Guys This is the way the my current architecture is designed. As you can see I am using an interface in conjunction with a base class to allow different xxxDAL classes to use the interface/base cla Read More

Views

10

Votes

0

Answers

1

August 17, 2011

unable to cast

Unable to cast object of type &#39;System.Collections.Generi c.List`1[S EODir.SEOC aptchaImag es]&#39; to type &#39;System.Collections.Generi c.List`1[S EODir.SEOC aptchaImag es]&#39;. Description: An Read More

Views

40

Votes

0

Answers

2

August 17, 2011

Specified cast is not valid error in sending e-mail with asp.net

I am trying to send an e-mail with &#160;file attachement using asp.net. I keep getting an error System.InvalidCastExceptio n: Specified cast is not valid in this line: SMTPMail.Send(myMail) How do I Read More

Views

21

Votes

0

Answers

21

August 17, 2011

reading xml into a custom built object

hi EE, i have a web service that I call which is fine. &#160;The problem I have is that I would like asp.net to read the xml data and place the content into my custom built object. The web service ret Read More

Views

36

Votes

0

Answers

37

August 17, 2011

Dynamic type casting

Hi all, I&#39;m trying to dynamically cast an object in order to keep my source brief. What I&#39;m trying to change, is depicted by the following procedure : procedure DoIt (fObject: TObject); begin Read More

Views

10

Votes

0

Answers

10

August 17, 2011

Problems working with COM object FAXCOMEXLib.FaxServerClass

I&#39;m trying to build a simple faxing application using FAXCOMEXLib. I used FAXCOMLib successfully, both locally and on the test box, but it doesn&#39;t have the status retrieval options I need. Her Read More

Views

35

Votes

0

Answers

5

August 17, 2011

Casting user defined types

Good morning. Hopefully an easy question and, assigning all my available points as it&#39;s one which has become a bit of a nightmare. I have an application that uses several user defined classes, all Read More

Views

14

Votes

0

Answers

6

August 15, 2011

Invalid cast from DateTime to Int32 - ASP.NET

I need some help with this Invalid Cast error I keep receiving. I am trying to execute a stored procedure in Sybase (my company is transferring one of my apps from SQL Server to Sybase, and I am not t Read More

Views

22

Votes

0

Answers

3

August 15, 2011

Casting a generic Object in C# to a custom Object

I have a situation where I need to declare a generic object globally in a Public class. Then later in a Switch statement I instantiate an instance of a custom DLL based on a value. &#160;There are abo Read More

Views

15

Votes

0

Answers

5

August 17, 2011

Microsoft, Visual Studio, 2005, C#, System.InvalidCastException: Specified cast is not valid.

I am returning values from a database using a TableAdapter and a DataView. &#160;However, when I run the program I get an error message saying that &quot;Specified cast is not valid.&quot; *********** Read More

Views

27

Votes

0

Answers

11

August 15, 2011

Collection of multiple types

I have a Silverlight 4 stack panel that I have been populating with textblock controls that are stored in a List collection. &#160;List&lt;Textblock&gt; controls = new List&lt;TextBlock&gt;(); I want Read More

Views

50

Votes

0

Answers

4

August 16, 2011

"System.InvalidCast Exception:Specified cast is not valid" when accessing a BLOB (image or text) field in SQl Server using the DAAB

This one is tough to explain, but let me try - We use DotNetNuke (DNN) as a framework for an internal web site. The newest version of DNN use the Microsoft Data Access Application Block (DAAB) describ Read More

Views

16

Votes

0

Answers

4

August 16, 2011

c++ class to convert avi to texture to wrap onto 3d object

The following c++ code fully initializes a 3d object in my project using the irrlicht.dll 3d engine. &#160;Following that I have a class which can convert an avi movie into a texture which can be disp Read More

Views

52

Votes

0

Answers

1

August 16, 2011

Need assistance figuring out an issue with the implementation of a .Net Delegate

Hi: I&#39;ve run into a runtime exception with trying to use a .Net Delegate. I&#39;m using MS VisualStudio 2008. I&#39;m essentailly trying to wrap access to a datagridview control with a delegate. U Read More

Views

19

Votes

0

Answers

4

August 16, 2011

Direct Cast

I have a book which says that DirectCast should be used when casting an object to an interface variable or casting an object to a derviced type variable. Can someone provide exmaples of both types of Read More

Views

14

Votes

0

Answers

4

August 16, 2011

Direct Cast + Value Types

Two Questions If a byte is a value type and directcast is the best way of changing from an object to a byte. Then would this also be the case for a byte array. The reason I am asking is that I read a Read More

Views

8

Votes

0

Answers

8

August 16, 2011