New instance of an unknown type?

I need to know how to find out what type an object is and then create a new object of that type. Can someone help me?

see:
http://livedocs.adobe.com/flex/3/langref/flash/utils/package-detail.html

Namely
getQualifiedClassName
and
getDefinitionByName

how would you do that though Sen? Got curious now.

I’m assuming this won’t work well

var sprite:Sprite = new Sprite();
var k:* = getQualifiedClassName(sprite);

k becomes a string, what’s the best approach of creating a new sprite from the definition inside the variable ‘k’ ?

getQualifiedClassName will get you the string name of an instance. to go the other way around, you’d use getDefinitionByName. This takes a string and converts it to a class reference. Use that return value with new and you got yourself a new instance of that same class (assuming any required constructor parameters were included).

var sprite:Sprite = new Sprite();
var k:String = getQualifiedClassName(sprite);
var c:Class = getDefinitionByName(k) as Class; // cast since Object can also be returned
var sprite2:Object = new c(); // can't accurately type (normally) since the class is dynamic; Object or * is fine
trace(sprite2 is Sprite); // true
trace( getQualifiedClassName(sprite2) == k ); // true

Thanks Sen,
I figured it out :slight_smile:


var myCustomObject:CustomObject = new CustomObject()
    
var type:String = getQualifiedClassName(myCustomObject);
var foundClass:Class = getDefinitionByName(type) as Class;
addChild(new foundClass());

Sweet, very nice, albeit confusing why you’re casting sprite2 as an object. (“can’t accurately type (normally) since the class is dynamic”) <- doesn’t quite click in my head as to why that is, but either way it’s working and thanks for the elaboration :slight_smile:

[QUOTE=sekasi;2356998]Sweet, very nice, albeit confusing why you’re casting sprite2 as an object. (“can’t accurately type (normally) since the class is dynamic”) <- doesn’t quite click in my head as to why that is, but either way it’s working and thanks for the elaboration :)[/QUOTE]

If you knew what the class type was to begin with, you wouldn’t need to use getDefinitionByName, you’d use the class name. And since you can’t type with variables, there’s no way to type the instance you’re creating

var myType = Sprite;
var myValue:myType; // FAIL!