Summary
A new feature of ActionScript 3, the language used in Flex, AIR, and Flash applications, is the ability to process custom annotations. Christophe Coenraets' latest blog post illustrates how such custom annotations can be used to create an object-relational mapping framework.
Advertisement
ActionScript 3 is Adobe's version of the next-generation JavaScript standard, and is the language for developing Flex, AIR, and Flash applications. Numerous new features in ActionScript 3 include reflection as well as the ability to define and process custom annotations on classes, methods, and properties.
Coenraets' technique lets you write an entity class in ActionScript as:
package
{
[Bindable]
[Table(name="contact")]
public class Contact
{
[Id]
[Column(name="contact_id")]
public var contactId:int;
[Column(name="first_name")]
public var firstName:String;
[Column(name="last_name")]
public var lastName:String;
public var address:String;
public var city:String;
public var state:String;
public var zip:String;
public var phone:String;
public var email:String;
}
}
In this example, Bindable is an annotation defined in the Flex framework to indicate that the target class or property serves as a source of data binding. The table and column annotations, however, are custom, to indicate, in this case, the target table and column names when persisting an instance of this class.
Coenraets shows that processing this annotation via ActionScript's reflection facility is straightforward: The class is introspected via the describeType() utility method that's part of the Flex framework. Given a class definition, that method produces an XML object—a native ActionScript 3 type—that provides all the metadata about the class, including the custom annotations. Given an Object o:
var c:Class = Class(getDefinitionByName(getQualifiedClassName(o)));
var xml:XML = describeType(new c());
var table:String =
xml.metadata.(@name=="Table").arg.(@key=="name").@value;
Having obtained the desired table name, Coenraets' simple entity manager example also determines the column names, connects to a local SQLite database, and performs simple CRUD operations on an ActionScript object.
As this example shows, ActionScript combines many features of other modern languages, provides functional programming capabilities, and even permits a choice between static and dynamic typing.
What are your favorite ActionScript 3 language features?