Static Code Blocks in ActionScript!

shot_1If you’re coming to the Flex world as a java user one thing you might miss is static code blocks. Until today I didn’t think this was possible in Flex/AS 3, but after a conversation with a coworker (Jim : psalterego.com) I found out static code blocks are possible.

First off, let me give a quick example of a static code block in java:

public class StaticCodeBlockExample {
    static {
        // my static code
    }
    ...
}

The code inside the static block is run when StaticCodeBlockExample is loaded. Among other tasks, this concept is pretty handy for initializing any static properties that might depend on utility classes to setup.

The AS 3 equivalent:

package {

import mx.managers.ISystemManager;

[Mixin]
public class StaticCodeBlockExample {
    public static function init(systemManager:ISystemManager) : void {
        trace("my static code block");
    }
}
}

As long as this class is referenced somewhere in your application, the init method gets called when the application is starting up. Essentially, we have a static code block!

4 thoughts on “Static Code Blocks in ActionScript!

  1. [ andy.mcintosh ]

    Yeah… what Tony said. I’m assuming the [Mixin] meta-data tag is what’s working the magic here? Do you know any more about it?

  2. Adam Flater - effectiveUI

    Jim knows about the magic… I’ll see if I can get him to commment.

  3. Jim Cheng

    It’s used in the Automation Framework classes mainly to register automation delegate implementations to component classes before any instances get the chance to be created. You can do a text search through the framework classes and find all the instances in the mx.automation.* namespace. It’s not all that interesting what they do in their init() calls, but you’ll get the general idea pretty quickly.

    The Flex Framework uses this scheme to “beat the developer to the punch” in terms of initialization such that any component instances are ready to be automated as soon as they can be instantiated either via direct ActionScript 3.0 code or through MXML.

    It’s a sneaky trick, but can be useful if you’re doing similar things like writing APIs for other AS3 developers where you need to ensure that some critical early initialization routines occur “silently” before they ever get a chance to use your API. For example, installing a logger (such as Adobe’s Automation Framework) would be a perfect use case for this.

Comments are closed.