Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get AS3 instance method reference from Class object

class Foo {
   public function bar():void { ... }
}

var clazz:Class = Foo;

// ...enter the function (no Foo literal here)
var fun:Function = clazz["bar"]; // PROBLEM: returns null

// later
fun.call(new Foo(), ...);

What is the correct way to do the above? The Java equivalent of what I want to do is:

Method m = Foo.class.getMethod("bar", ...);
m.invoke(new Foo(), ...);

Actual code (with workaround):

class SerClass {

    public var className:String;
    public var name:String;
    private var ser:String = null;
    private var unser:Function = null;

    public function SerClass(clazz:Class):void {

        var type:XML = describeType(clazz);

        className = type.@name;

        // determine name
        name = type.factory.metadata.(@name=="CompactType").arg.(@key=="name").@value;

        // find unserializer
        var mdesc:XML = XML(type.method.metadata.(@name=="Unserialize")).parent();
        if (mdesc is XML) {
            unser = clazz[mdesc.@name];
        }

        // find serializer
        var sdesc:XML = XML(type.factory.method.metadata.(@name=="Serialize")).parent();
        if (sdesc is XML) {
            ser = sdesc.@name;
        }


    }
    public function serialize(obj:Object, ous:ByteArray):void {
        if (ser == null) throw new Error(name + " is not serializable");
        obj[ser](ous);
    }
    public function unserialize(ins:ByteArray):Object {
        if (unser == null) throw new Error(name + " is not unserializable");
        return unser.call(null, ins);
    }
}
like image 976
Bart van Heukelom Avatar asked May 23 '11 13:05

Bart van Heukelom


2 Answers

Here the function bar only exist when your class is instanciated :

var foo:Foo = new Foo()
var fun:Function = foo.bar // <-- here you can get the function from the new instance

if you want to access it directlty you have to make it static:

class Foo {
 public static function bar():void{ ... }
}

now you can access your function from the class Foo:

var fun:Function = Foo.bar

or

var clazz:Class = Foo
var fun:Function = clazz["bar"]
like image 85
Patrick Avatar answered Oct 22 '22 04:10

Patrick


I am not sure about what you are intending to do.

However AS3Commons, especially the reflect package have API's that let you work with methods, instances and properties of a class.

There are also API methods to create instances of certain class types on the fly and call their respective methods.

Cheers

like image 23
Dennis Jaamann Avatar answered Oct 22 '22 03:10

Dennis Jaamann