as3commons 在运行时生成函数调用

as3commons generate function call at runtime

出于某些原因,我在运行时生成了一个 class,它有一个现有的超级 class 和一个受保护的成员,并实现了一个现有的接口。接口的每个方法(和访问器)也需要生成。我努力的地方是用正确的操作码填充方法体。 这是一个我想生成或翻译成操作码的例子:

public function myFunction(arg1:String, arg2:int):Boolean
{
    return member.my_namespace::myFunction(arg1, arg2);
}

所有信息都可用,例如函数名称、参数、return 类型和命名空间。而且我能够创建函数本身和 return 默认值,就像在 as3commons tests/examples

中看到的那样

也许我应该使用 as3commons 以外的其他库?

我自己找到了答案。我所缺少的只是(正确)使用 QualifiedName 来访问成员及其功能。我只删除了名称空间。这就是我在模板代码中修改的所有内容:

public function myFunction(arg1:String, arg2:int):Boolean
{
    return member.myFunction(arg1, arg2);
}

以下是生成该函数所需的源代码,包括方法主体的操作码:

var abcBuilder:AbcBuilder = new AbcBuilder();

//build the class with the super class and the interface
var packageBuilder:IPackageBuilder = abcBuilder.definePackage("my.package");
var classBuilder:IClassBuilder = packageBuilder.defineClass("RuntimeClass", "my.package.BaseClass");
classBuilder.implementInterface("my.package.IMyInterface");

//build the function
var methodBuilder:IMethodBuilder = classBuilder.defineMethod("myFunction");
methodBuilder.returnType = "Boolean";
methodBuilder.visibility = MemberVisibility.PUBLIC;
methodBuilder.isFinal = true;

//add the parameters
methodBuilder.defineArgument("String");
methodBuilder.defineArgument("int");

//here begins the method body with the opcode
methodBuilder.addOpcode(Opcode.getlocal_0);
methodBuilder.addOpcode(Opcode.pushscope);
//call the member "member"
methodBuilder.addOpcode(Opcode.getlex, [new QualifiedName("member", LNamespace.PUBLIC)]);
//access to the function args
methodBuilder.addOpcode(Opcode.getlocal_1);
methodBuilder.addOpcode(Opcode.getlocal_2);
//call the function at the above prepared member with the prepared args
methodBuilder.addOpcode(Opcode.callproperty, [new QualifiedName("myFunction", LNamespace.PUBLIC), 2]);
//return the result
methodBuilder.addOpcode(Opcode.returnvalue);

//fire at own will
abcBuilder.addEventListener(Event.COMPLETE, loadedHandler);
abcBuilder.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
abcBuilder.addEventListener(IOErrorEvent.VERIFY_ERROR, errorHandler);
abcBuilder.buildAndLoad();

我不保证代码有效。我在我自己的项目中用一些动态的东西和循环调整了它,它工作得很好。 我使用的库(d)是:

  • as3commons-bytecode-1.1.1
  • as3commons-lang-0.3.7
  • as3commons-logging-2.7
  • as3commons-reflect-1.6.4

as3commons downloads

下全部可用