我一直试图通过创建一个新的 ApplicationDomain 并将其传递给加载程序上下文来动态加载库。我做错的是存储对该 ApplicationDomain 的引用并尝试从该引用中获取定义。出于某种原因,它返回 null。通过实现paleozogt的答案并改变它以动态加载swf,我最终得到了正确的代码,它不使用对ApplicationDomain的存储引用,而是从加载器的contentLoaderInfo中获取它。
如果你想动态加载库,下面是代码:
package
{
import flash.display.Loader;
import flash.events.Event;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
public class AlchemyDynamicLoad
{
private var _library:Object;
private var _loader:Loader;
public function AlchemyDynamicLoad()
{
var loaderContext:LoaderContext = new LoaderContext(false, new ApplicationDomain());
var request:URLRequest = new URLRequest("../assets/mylib.swf");
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
_loader.load(request, loaderContext);
}
private function completeHandler(event:Event):void
{
// NOTE: Storing a reference to the application domain you feed to the loaderContext and then trying to get the
// definition from that reference is not going to work for some reason. You have to get the applicationDomain
// from the contentLoaderInfo, otherwise getDefinition returns null.
var libClass:Class = Class(_loader.contentLoaderInfo.applicationDomain.getDefinition("cmodule.mylib.CLibInit"));
_library = new libClass().init();
}
}
}
如果你想嵌入它,这里是代码(paleozogt's answer):
package
{
import flash.display.Loader;
import flash.events.Event;
public class AlchemyStaticLoad
{
[Embed(source="../assets/mylib.swf", mimeType="application/octet-stream")]
private static var _libraryClass:Class;
private var _library:Object;
private var _loader:Loader;
public function AlchemyStaticLoad()
{
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
_loader.loadBytes(new _libraryClass());
}
private function completeHandler(event:Event):void
{
var libClass:Class = Class(_loader.contentLoaderInfo.applicationDomain.getDefinition("cmodule.mylib.CLibInit"));
_library = new libClass().init();
}
}
}