fenomas
fenomas

Reputation: 11139

Can AS3 vectors be declared with a type reference?

Instead of this:

var v:Vector.<String> = new Vector.<String>();

is there any way to do something like this?

var myType:Class = String;
var v:Vector.<myType> = new Vector.<myType>();

Obviously that doesn't work as written, but hopefully you get the idea.

Upvotes: 4

Views: 1300

Answers (3)

nooker
nooker

Reputation: 1

I found sort of a way to create Vectors dynamically. Instead of passing the type as class you pass the whole vector as class, like:

public function createVector (vectorType:Object):Object
{
    return new vectorType();
}

var v:Vector.<String> = createVector(Vector.<String>);

Or you can copy a vector like this:

public function getCopy (ofVector:Object):Object
{
    var copy:Object = new ofVector.constructor;

    return copy;
}

Upvotes: 0

Richard Szalay
Richard Szalay

Reputation: 84824

Short answer is try grapefrukt's answer and see.

However, I don't think it's possible at a bytecode level. The problem related to how generics (Vectors) are constructed. Basically the bytecode for creating an instance of Vector<> goes:

GenericDefinitionType (Vector) + GenericParameter (int) -> GenericType
Coerce (cast) GenericType as KnownGenericType (eg. "Vector.<int>")

So the issue is not in the creation, since GenericParameter is just a multiname (which can be dynamic). The issue is in the coercion to the known vector type (actually registered as "Vector.<int>" for example) since there is no known vector type.

See my post on how Vectors work in bytecode for the geeky details.

Upvotes: 4

grapefrukt
grapefrukt

Reputation: 27045

This is untested, but I can't see why it shouldn't work:

import flash.display.Sprite;
import flash.utils.getDefinitionByName;

var ClassReference:Class = getDefinitionByName("flash.display.Sprite") as Class;
var v:Vector.<ClassReference> = new Vector.<ClassReference>();

Upvotes: -1

Related Questions