Flex Quick Tip: Printing an Objects’ contents

You quickly learn in Actionscript 3 that tracing an objects’ contents is not always that simple.  Commands such as trace(myObject); often yeild the highly infuriating [object Object] return, which tells you mostly nothing of what you actually wanted to know.  After that you can move on to more advanced trace logic, like the handy;

for(var i in n) {
    trace(i+":"+n[i]);
}

But that’s a lot of stuff to type, and often yeilds infuriatingly long stacks of parameter traces.

Flex can make things a little easier, with this useful utility class, the cunningly named ObjectUtil class.  Simply import the class (import mx.utils.ObjectUtil;) and call the following method; trace(ObjectUtil.toString(myObject)); and you’ll get a nice output of all the properties of your object.

Kudos to flextutor.org for this, in their original post “How to print an objects’ contents in Flex.”  I thought I’d repost it here though, not least because there seems to be an issue loading their site as I’ m writing this article.

About James

James is a Senior New Media Developer at MMT Digital, and has BA(Hons) in Design for Interactive Media from the University of Gloucestershire. He loves designing and producing all sorts of website and Flash-related things, as well as prattling on about technologies.Day-to-day he works with Flash, Dreamweaver, Director, Microsoft Office Sharepoint Server 2007 (MOSS) and in his spare time he mucks about in Flex and Wordpress.Follow James on Twitter.

4 Responses to “Flex Quick Tip: Printing an Objects’ contents”

  1. Kristofer Joseph 15th June, 2009 at 9:29 pm # Reply

    This is not true for all object. For instance the NetStream info object cannot be traversed in this way. Instead you would need to use describeType();

    package {
    import flash.display.Sprite;
    import flash.utils.describeType;

    public class DescribeTypeExample extends Sprite
    {
    public function DescribeTypeExample()
    {
    var child:Sprite = new Sprite();
    var description:XML = describeType(child);
    trace(description..accessor.@name.toXMLString());
    }
    }
    }

    As described here: http://livedocs.adobe.com/flex/2/langref/flash/utils/package.html#describeType()

  2. Rory 25th January, 2010 at 9:13 pm # Reply

    Thanks, needed help printing the contents of my Object (associative array) and this did the trick. And, the other blog where this appeared still does not load, so thanks for the “re-post”

  3. Pim 11th March, 2010 at 1:29 pm # Reply

    Very usefull information. Saved me alot of time so thank you!

  4. cole 20th January, 2011 at 9:38 pm # Reply

    Fantastic! Thank you! Just what I’ve been looking for!

Leave a Reply

Note: This post is over 2 years old. You may want to check later in this blog to see if there is new information relevant to your comment.