Cameron A. Ellis
Cameron A. Ellis

Reputation: 3881

pass class as parameter, then instantiate from class

I've done this before, but i can't quite remember the syntax.

What i've got (simplified):

function createText(clazz:Class)
{
    var font:Font = new clazz(); //throws Instantiation attempted on a non-constructor.
}

I believe this can be done without using getQualifiedClassName, but its been a long time. Any help appreciated.

Upvotes: 3

Views: 5287

Answers (3)

Cameron A. Ellis
Cameron A. Ellis

Reputation: 3881

Turns out I hadn't given the font a class name in CS3. So yes,I was passing null.

Upvotes: 0

James Fassett
James Fassett

Reputation: 41044

You are probably passing null to the function.

package
{

import flash.display.Sprite;

public class ClassTest extends Sprite
{
    function ClassTest()
    {
        makeObject(Object);
        makeObject(Sprite);
        makeObject(null);
    }

    private function makeObject(type:Class):void
    {
        trace(typeof type);
        var obj:* = new type();
        trace(typeof obj);
        trace("");
    }
}

}

This outputs:

object
object

object
object

object
TypeError: Error #1007: Instantiation attempted on a non-constructor.
    at ClassTest/makeObject()
    at ClassTest()

Upvotes: 7

Benoit Jadinon
Benoit Jadinon

Reputation: 1161

how are you passing the class to the function ? the calling line should have trown an error in the first place if the wanted class wasn't available, this is weird.

can you post the real code ?

here a trick for loading a class compiled in an external swf

var clazz:Class = this.yourLoader.contentLoaderInfo.applicationDomain.getDefinition("yourClassName") as Class;

Upvotes: 1

Related Questions