谷粒的泥坑

🌿谷粒的生活笔记 —— 在数字世界的泥坑中,播种代码、文字的种子,静待每一份热爱自然生长

通过getDefinitionByName获取外部价值的swf其中的类的具体操作

在Adobe AIR项目中,加载本地SWF后,可以通过getDefinitionByName或更可靠的方式获取其中的类。以下是具体实现步骤:

实现步骤:

  1. 设置LoaderContext:加载时指定应用程序域,确保类定义可访问。
  2. 加载SWF文件:使用Loader加载本地SWF,注意路径协议(如app:/file://)。
  3. 监听加载完成事件:在事件处理中获取SWF的应用程序域。
  4. 获取类定义:通过ApplicationDomain的getDefinition方法或getDefinitionByName获取类。

在Adobe AIR项目中,加载本地SWF后,可以通过getDefinitionByName或更可靠的方式获取其中的类。以下是具体实现步骤:

实现步骤:

  1. 设置LoaderContext:加载时指定应用程序域,确保类定义可访问。
  2. 加载SWF文件:使用Loader加载本地SWF,注意路径协议(如app:/file://)。
  3. 监听加载完成事件:在事件处理中获取SWF的应用程序域。
  4. 获取类定义:通过ApplicationDomain的getDefinition方法或getDefinitionByName获取类。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private var loader:Loader = new Loader();

// 加载SWF
private function loadSWF():void {
var url:String = "app:/assets/external.swf"; // 本地SWF路径
var urlReq:URLRequest = new URLRequest(url);
// 设置应用程序域为当前域,使类定义可访问
var loaderContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
loaderContext.allowLoadBytesCodeExecution = true; // AIR中可能需要
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSwfLoaded);
loader.load(urlReq, loaderContext);
}

// SWF加载完成处理
private function onSwfLoaded(event:Event):void {
var loaderInfo:LoaderInfo = event.target as LoaderInfo;
var appDomain:ApplicationDomain = loaderInfo.applicationDomain;

try {
// 方法1:通过ApplicationDomain获取(推荐)
var MyClass:Class = appDomain.getDefinition("com.example.MyClass") as Class;

// 方法2:若加载到当前域,也可使用getDefinitionByName
// var MyClass:Class = getDefinitionByName("com.example.MyClass") as Class;

var instance:Object = new MyClass();
if (instance is DisplayObject) {
addChild(instance as DisplayObject);
}
} catch (e:Error) {
trace("无法获取类定义: " + e.message);
}
}

关键点:

应用程序域设置:使用ApplicationDomain.currentDomain将SWF类合并到当前域,便于访问。若担心命名冲突,可创建子域new ApplicationDomain(ApplicationDomain.currentDomain),但需从子域中获取类。
类导出:确保SWF中的目标类已导出(如Flash中设置“导出到帧”),避免被编译器优化。
完全限定名:使用类的完整包路径(如com.example.MyClass)。
异常处理:捕获可能的错误,如类不存在或访问权限问题。

注意事项:

AIR权限:加载本地文件时,路径需正确(如使用app:/访问应用目录)。
安全沙箱:确保跨沙箱访问权限,本地SWF通常无此问题。
LoaderContext配置:在AIR中可能需要allowLoadBytesCodeExecution = true以允许执行加载的代码。

通过以上步骤,即可在加载完成后获取并实例化SWF中的类。推荐使用ApplicationDomain.getDefinition()方法,直接通过加载的应用程序域获取类定义,避免全局域污染和潜在冲突。