Loop Through All Properties of a Class

package {
	
	import flash.display.Sprite;
	import flash.utils.describeType;
	
	public class Main extends Sprite {
		
		public function Main(){
		    var test:Test = new Test();
			var desc:XML= describeType(test);
			// public vars
			for each (var v:XML in desc.variable){
				trace(v.@name, test[v.@name]);
			}
			// getters
			for each (v in desc.accessor){
				trace(v.@name, test[v.@name]);
			}
		}
		
	}
}

class Test{
	public var a:Number = 123;
	public var b:Number = 100;	 
	private var _getterVal:Boolean = false;
	public function get getter():Boolean{
		return _getterVal;
	}
}
/*
outputs:
b 100
a 123
getter false
*/

I’m working on a few libraries, QuickBox2D and a library for auto-generated UI stuff… this technique just came in handy. It shows how to use describeType() to loop through public vars and getters of a given class.

The title of this post should really be Loop Through All PUBLIC properties of a class…. but it was long enough as it is….
Note: this should be run as document class

3 comments

  1. Hi,

    I’ve an issue on my side.
    In the context below, getter = null…
    Have you an idea why ?

    class AbstractTest
    {
    public function toString():String
    {
    var xml:XML = describeType(this);

    var properties:String = _getProperties(xml);
    var accessors:String = _getAccessors(xml);

    var s:String = xml.@name;
    s+= ” | ” + properties + ” | ” + accessors;
    return s;
    }

    private function _getProperties(xml:XML):String
    {
    var aProperties:XMLList = xml.variable.@name;
    var s:String = “Properties -> “;
    for(var i:String in aProperties)
    {
    s+= aProperties[i] + ” = “+ this[aProperties[i]] +” / “;
    }
    return s;
    }

    private function _getAccessors(xml:XML):String
    {
    var aAccessors:XMLList = xml.accessor.@name;
    var s:String = “Accessors -> “;

    for(var i:String in aAccessors)
    {
    s+= aAccessors[i] + ” = “+ this[aAccessors[i]] +” / “;
    }
    return s;
    }
    }

    class TestBase
    {
    public function get getter():Boolean
    {
    return _getterVal;
    }
    }

    class Test extends TestBase
    {
    public var a:Number = 123;
    public var b:Number = 100;
    }

  2. Forget it !
    Getter returns the correct variable, but when I pass value to the constructor, getter variable was not initialized…
    Shame on me !

Leave a Reply

Your email address will not be published. Required fields are marked *