Marc Hughes


Home
Blog
Twitter
LinkedIn
GitHub
about
I am a developer from a bit west of Boston.

Easy object reflection with Spicelib

02 Apr 2009

I use Parsely in some of my projects for an MVC / IoC framework.  Parsley relies on Spicelib, so you get that functionality "for free" if you're using Parsley.  Lately, I've started using some of the Spicelib relflection API and I'm impressed with it.  It acts as a wrapper around the flash.utils.describeType method to describe objects at runtime.

Here's an example that loops through the properties of an object...

var ci:ClassInfo = ClassInfo.forInstance( component );
for each ( var property:Property in ci.getProperties() )
{
  trace( property.name );
  trace(property.type.name );
  trace( property.readable );
  trace( property.writable );
}
You can get a whole lot of info about classes, methods, and properties, you can read the docs to see.

One useful function of this, is you can get at any custom metadata tags that you've created.  In that loop above, I could have something like this:

for each ( var meta:Metadata in property.getAllMetadata() )
{
  if( meta.name == "AnimationProperty" )
  {
    // do something with this property
  }
}
Then, if I had a class like this:
public class StupidClass
{
    [AnimationProperty]
    public var thisIsAnAnimationProperty:Number;

public var thisIsNOTAnAnimationProperty:Number; }

We could differentiate between those two properties.

Read this blog entry for a little info on how to do custom metadata.