When you want to cast type on the class instance to use its class methods but you don’t know the type for this class instance since you only have the reference to it…
In “flash.utils” package, there are 2 functions that is very useful for this kind of situation, they are “getQualifiedClassName” and “getDefinitionByName”.
“getQualifiedClassName” takes any values including all available ActionScript types, object instances, primitive types such as uint, and class objects. And returns a string containing the fully qualified class name. E.g.- if we have “Image” class in “com.app” package:
package {
// Import class
import flash.utils.*;
import com.app.Image;
// Main class
public class Main extends Sprite {
// Constructor
function Main() {
var myImg:Image = new Image();
trace(getQualifiedClassName(myImg));
}
}
}
You will get “com.app::Image” from output panel and you can use regular expressions to replace “::” with “.” so you get “com.app.Image” instead.
“getDefinitionByName” takes the fully qualified class name string and returns a reference to the class object of the class.
package {
// Import class
import flash.utils.*;
import com.app.Image;
// Main class
public class Main extends Sprite {
// Constructor
function Main() {
trace(getDefinitionByName("com.app.Image"));
}
}
}
You will get “[class Image]” from output panel.
So combining those 2 functions, we can easily get the class reference from the class instance which we don’t know its type is.
Suppose the “Image” class implements interface “IImage” and “Image” class has a method called “transition” which “IImage” doesn’t. If we want to use “transition” method, we will need to cast “Image” type on the instance. To get the “Image” instance reference, we use View.getInstance().getRef(”Img1″) for this example and it returns “IImage” type.
package {
// Import class
import flash.utils.*;
import com.app.*;
// Main class
public class Main extends Sprite {
// Constructor
function Main() {
// Get Image instance reference
var myImg:IImage = View.getInstance().getRef("Img1");
// Use regular expressions to replace "::" with "."
var myPattern:RegExp = /::/;
var className:String = getQualifiedClassName(myImg).replace(myPattern, ".");
// Get reference to the class
var myImgClass:Class = getDefinitionByName(className) as Class;
// Call transition method
(myImg as myImgClass).transition();
}
}
}
Hope it will help you when developing the flash application:)
No user commented in " Casting Type Dynamically "
Follow-up comment rss or Leave a TrackbackLeave A Reply