Tip: Convert An Object To A Class By Name

Have you ever had to convert an object into a class based on its name? If you've got a string representation of the object (like its class identifier from the library) you can convert it to the data type that you'd like. All you have to do is use the handy little method called getDefinitionByName().

Here is an example of a sound that is in a library with the class field set to MySound:

Actionscript:
  1. var SoundRef:Class = getDefinitionByName("MySound") as Class;
  2. var _sound:Sound = new SoundRef();
  3. _sound.play();

What this does is defines the class SoundRef as a "holder" for your class name using getDefinitionByName(). You can then create a variable that is the type of object you want to use and set it as your SoundRef class. Then, you can use that variable to run methods of the class on it. You're essentially doing the same thing as casting the variable but you're using the name of the class rather than casting it directly. This is useful if, for instance, you are looping through an array of class names that you know exist and want to convert them to their type. This is exactly the example that I gave to Stephen Matthews in my comments on my post about attaching sounds from the library.

Actionscript:
  1. for (var so in _sfxArr)
  2. {
  3.     var ClassRef:Class = getDefinitionByName(_sfxArr[so]) as Class;
  4.  
  5.     var _tempSOUND:Sound = new ClassRef();
  6.     _tempSOUND.play();
  7.  
  8.     _soArr.push(_tempSOUND);
  9. }

If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.

3 Comments

good site about flash .visit my blog also and follow or comment it.

Interesting! I'll try and make use of that in my next project.

Great site :)

Great tip!

Leave a comment

(required)

(required)