Generic toString for any object or class

Posted 26 July 2010 by

Update:

This ToStr class has been revamped here, check it out!

Old Post Continued:

If you are like me, lazy to build custom “toString” functions the whole time, then this is the perfect little snippet for you. The ToStr class will output any object or class into a String formatted the same way as the Event class does, but with a few improvements. The ToStr class works especially well for Events and VOs. Please note that this class does not focus on performance, it’s only goal is to make debugging easier and quicker.

Event standard toString();

[Event type="complete" bubbles=false cancelable=false eventPhase=2]

Event with ToStr class

[Event | bubbles=false | cancelable=false | currentTarget=[object MovieClip] | eventPhase=2 | target=[object MovieClip] | type=complete]

How to use

Construct a new instance of the ToStr class and pass it the object/instance to be traced and/or whether you’d like it omit null values. The ToStr class implements it’s own toString function, thus the String is only created once you cast to String, call toString(); or even if you concatenate to another String.

Let’s take a VO example:

First we have the VO class with a few public variables and the our awesome toString function.

package
{
	import mu.utils.ToStr;

	/**
	 * @author Matan Uberstein
	 */
	public class LoginRequestVo
	{
		public var username : String;
		public var password : String;
		public var couponId : int;
		public var rememberMe : Boolean;

		public function toString() : String
		{
			return String(new ToStr(this));
		}
	}
}

Now we create a simple class that we can compile and see the output.

package
{
	import flash.display.Sprite;

	/**
	 * @author Matan Uberstein
	 */
	public class ToStrTester extends Sprite
	{
		public function ToStrTester()
		{
			var vo : LoginRequestVo = new LoginRequestVo();
			vo.username = "MatanUbe";
			vo.password = "super@!";
			vo.couponId = 88;
			vo.rememberMe = true;

			trace(vo);
		}
	}
}

Resulting output:

[LoginRequestVo | couponId=88 | password=super@! | rememberMe=true | username=MatanUbe]

Things to keep in mind

  • You can construct the ToStr class at any time for any object.
  • Dynamic properties will also be traced.
  • For debugging only.

Source

package mu.utils
{
	import flash.utils.describeType;

	/**
	 * @author Matan Uberstein
	 */
	public class ToStr
	{

		/**
		 * @private
		 */
		protected var _obj : Object;

		protected var _omitNullValues : Boolean;

		/**
		 * @param obj Object gets stored for use when "toString" is called.
		 */
		public function ToStr(obj : Object = null, omitNullValues : Boolean = true)
		{
			_obj = obj;
			_omitNullValues = omitNullValues;
		}

		/**
		 * @return String representing of the object passed into constructor.
		 */
		public function toString() : String
		{
			if(_obj)
			{
				//Get the description of the class
				var description : XML = describeType(_obj);
				var properties : Array = [];

				//Get accessors from description
				for each(var a:XML in description.accessor)
				{
					properties.push(a.@name.toString());
				}

				//Get variables from description
				for each(var v:XML in description.variable)
				{
					properties.push(v.@name.toString());
				}

				//Get dynamic properties if the class is dynamic
				if(description.@isDynamic == "true")
				{
					for(var p : String in _obj)
					{
						properties.push(p);
					}
				}
				//Sort
				properties.sort();

				//Build the string with properties and values
				var desName : String = description.@name;
				var str : String = "[";

				str += (desName.search("::") == -1) ? desName : desName.slice(desName.search("::") + 2, desName.length);

				var pL : int = properties.length;
				for(var i : int = 0;i < pL;i++)
				{
					var mustOutput : Boolean = true;

					if(_omitNullValues)
					{
						try
						{
							if(_obj[properties] == null || _obj[properties] == undefined || _obj[properties] == "")
								mustOutput = false;
						}catch(err : Error)
						{
							mustOutput = false;
						}
					}

					if(mustOutput)
						str += " | " + properties + "=" + _obj[properties];
				}
				str += "]";

				return str;
			}

			return "";
		}
	}
}

Post Details

  • http://www.bangersandflash.net jassa

    Nice work – this’ll come in handy.

    I’m usually too lazy to write custom toString functions, and even lazier to post about it, so thanks ;)

    • admin

      Haha, don’t we all feel like that some times. :)

      Thanks for the comment, you are officially the first person to comment on my new blog. :D

      Glad you like!

  • John K

    Doesnt compile, whats this line?
    if(_obj[properties] == null || _obj[properties] == undefined || _obj[properties] == “”)                                mustOutput = false;

    The ‘s confuse it.