来自getDefinitionByName的奇怪行为

时间:2009-08-20 20:02:47

标签: flex actionscript classloader

我已经创建了一个类,它根据传递给它的名称加载它的子类。该函数使用getDefinitionByName,获取类类型并实例化它,如果类是拥有此方法的类的子类型,则返回它。子类型都是扩展基类的mxml文件,以简化实例化控件。

但是,在我传递一个完全限定名称的情况下,它在我的单元测试中工作,但是当我在我的应用程序的上下文中执行它时失败。 getDefinitionByName中是否存在使得它在不同的执行上下文中表现不同的问题?有没有更简单的方法来加载类的限定名称?

static public function loadDisplay(className:String, extendedClassName:String = null):FeatureDisplay
{
    try
    {
        trace("Loading", className);
        var cls:Class = getDefinitionByName(className) as Class;
        var display:FeatureDisplay = new cls() as FeatureDisplay;
        if(display)
        {
            return display;
        }
        else
        {
            trace(className, "is not a subclass of FeatureDisplay");
            return null;
        }
    }
    catch(error:Error)
    {
        trace("Error loading", className);
        trace("Error:", error.message);
    }
    return null;
}

2 个答案:

答案 0 :(得分:3)

我的第一个问题是你是否显式地使用任何一个类?如果您实际上没有使用类,即使它已导入,ActionScript也可能不会在swf中保留类定义的副本。

也就是说,如果可以避免使用getDefinitionByName,describeType,getQualifiedClassName或getQualifiedSuperclassName,最好避免使用它们。它们是记忆猪,通常最好避免它们。 (除非您无法控制在运行时将使用哪些类,并且 HAVE 将通过getDefinitionByName使用)。

我的建议是你用一个swtich替换getQualifiedClassName ... case:

// Import the subclasses.
import path.to.SpriteFeatureDisplay;
import path.to.OtherFeatureDisplay;

class FeatureDisplay extends Sprite{

   //Make one public static const per class.
   public static const SPRITE_FEATURE_DISPLAY:String = "sprite_feature_display";
   public static const OTHER_FEATURE_DISPLAY:String  = "other_feature_display";

   public static function loadDisplay(  className:String, 
                                        extName:String = null ):FeatureDisplay
   {
      trace("Loading", className);

      // This will ensure that each of the classes is stored in the swf
      // it will behave faster, and it is less prone to errors (note that 
      // try...catch is not needed).
      swtich( className )
      {
          case SPRITE_FEATURE_DISPLAY:
            return new SpriteFeatureDisplay();
          case OTHER_FEATURE_DISPLAY:
            return new OtherFeatureDisplay();
          default:
            trace( "Requested class " + className + " could not be created..." +
            "\nPlease make sure that it is a subclass of FeatureDisplay" );
            return null;
      }
      return null;
   }
}

答案 1 :(得分:2)

仅供参考,我已经看到了以下保持Flex源代码中使用的类的方法:

// References.cs

// notice the double reference: one to import, the other to reference
import package.to.ClassA; ClassA;
import package.to.ClassB; ClassB;
import package.to.ClassC; ClassC;

当然,您仍然需要在某处引用“参考”类。