How to get type of variable? and instantiate it?

孤人 提交于 2019-12-24 03:36:12

问题


I am trying to make a function that opens a window but makes sure the same window is not already open. I want to be able to pass it a non-instantiated var or an instantiated var and it work either way. If the window is already open it closes it then reopens it.

So I need a way to pass a variable of type Window or a subclass if it, and instantiate the proper subclass.

I am looking for something like this:

public function openWindowOnce(window:Window):void
{
    if(isOpen(window))
    {
        closeIfOpen(window);
    }
    window = new Window(); /**<-- THIS LINE window can also be a sublcass of window, 
                             *    I want to instatiate the correct sublass,
                             *    I also want to make sure that it is a Window or a
                             *    Sublcass of window before I instatiate it.
                             */ 
    window.open();
}

Thanks!


回答1:


You can try using a combination of flash.utils.getDefinitionByName(), flash.utils.getQualifiedClassName() and ClassFactory to achieve the result.

var className:string = getQualifiedClassName(object); //returns the class name    
var classObj:Class = getDefinitionByName(className) as Class; //get a Class object
var factory:IFactory = new ClassFactory(classObj);// get a Class factory    
var newObj:Object = factory.newInstance();


来源:https://stackoverflow.com/questions/1137730/how-to-get-type-of-variable-and-instantiate-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!