I've got a method that accepts a parameter of type Class
, and I want to only accept classes that extend SuperClass
. Right now, all I can figure out to do is this, which does a run-time check on an instance:
public function careless(SomeClass:Class):void {
var instance:SomeClass = new SomeClass();
if (instance as SuperClass) {
// great, i guess
} else {
// damn, wish i'd have known this at compile time
}
}
Is there any way to do something like this, so I can be assured that a Class
instance extends some super class?
public function careful(SomeClass:[Class extends SuperClass]):void {
var instance:SuperClass = new SomeClass();
// all is good
}
Your requirements:
and
Can be met by passing in an instance of the class you need, and using the Object.constructor() method.
More reading here.
If you are going to instantiate it anyway, why not accept an object instead which allows you to type it to
:SuperClass
?Not too much of a problem there as far as your code goes. There are a few differences though:
All that is solved by the factory pattern. Pass a factory as the parameter that produces
SuperClass
objects.It is possible but it's expensive. You can use on a Class (not instance) the:
You then get an XML with a bunch of information including inheritance for that class. Like I said it's an expensive process and probably creating an instance and checking it will be in most cases faster.
You can't do that in ActionScript 3. In languages like C# you can do something like (forgive me if the syntax is off):
But AS3 does not have 'generics'. Unfortunately the only way I know how to do what you want is the way you have already done.
A pattern that might be more suitable for your use case might be something like:
The only way to have static type checking in ActionScript 3 is to provide an instance of a class.