我有xml-structure,我加载了程序的大部分数据。在这种情况下,我想实例化一个在xml中指定的类。我想我可以在xml中编写类的名称,然后实例化它并将参数传递给它。事实证明这并不容易!
我尝试了这样的代码:
//special objects
for each (o in xml.Objects[0].special)
{
p.x = o.@x;
p.y = o.@y;
s.x = o.@width;
s.y = o.@height;
trace(o.@classname);
//var type:Class = o.@classname as Class;
var type:Class = getDefinitionByName(String(o.@classname)) as Class;
trace(type);
objectArray.push(new type(p, s));
trace("special");
}
正如您所看到的,我在xml-file中的classname属性中有我的类的名称。我设法用getDefinitionByName获取定义(至少下一个跟踪显示正确的类名)但是当我尝试实例化它并将其推入数组时,我得到一堆错误开始
错误#2136:SWF文件文件:///Users/tuomas/Dropbox/Flash/ScorpionBox/bin-debug/ScorpionBox.swf包含无效数据。
知道我应该怎么做?
答案 0 :(得分:4)
假设您的XML类型定义由getQualifiedClassName()
获取的限定名称组成,请根据需要实例化类型并应用属性。
xml定义的显示对象的实例化:
package
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.utils.getDefinitionByName;
public class XmlParser extends Sprite
{
public var xml:XML = <objects>
<object type="flash.display::Sprite" x="0" y="0" width="100" height="100" />
<object type="flash.display::MovieClip" x="0" y="0" width="100" height="100" />
</objects>;
public function XmlParser()
{
for each (var object:XML in xml.children())
{
var type:Class = getDefinitionByName(object.@type) as Class;
var instance:DisplayObject = new type();
instance.x = object.@x;
instance.y = object.@y;
instance.width = object.@width;
instance.height = object.@height;
addChild(instance);
}
}
}
}
您还可以在序列化为XML时描述Type对象,然后通过迭代XML的属性将属性应用回对象实例,例如:
package
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.utils.getDefinitionByName;
public class XmlParser extends Sprite
{
public var xml:XML = <objects>
<object type="flash.display::Sprite" x="0" y="0" width="100" height="100" />
<object type="flash.display::MovieClip" x="0" y="0" width="100" height="100" />
</objects>;
public function XmlParser()
{
for each (var object:XML in xml.children())
{
var type:Class = getDefinitionByName(object.@type) as Class;
var instance:DisplayObject = new type();
addChild(instance);
for each (var attribute:XML in object.@*)
{
if(attribute.name() == "type") { continue; }
trace("setting: " + attribute.name() + " = " + attribute.toXMLString());
instance[attribute.name().toString()] = attribute.toXMLString();
}
}
}
}
}