1

出于某种原因,我在运行时生成了一个类,该类具有一个带有受保护成员的现有超类并实现了一个现有接口。接口的每个方法(和访问器)也需要生成。我苦苦挣扎的一点是用正确的操作码填充方法体。这是我要生成或转换为操作码的示例:

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

所有信息都可用,例如函数名称、参数、返回类型和命名空间。而且我能够创建函数本身并返回一个默认值,就像在as3commons 测试/示例中看到的那样

也许我应该使用除 as3commons 之外的另一个库?

4

1 回答 1

0

我自己找到了答案。我所缺少的只是(正确)使用 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 下载

于 2015-12-29T21:00:18.877 回答