getDefinitionByName(), ReferenceError: Error #1065: Variable is not defined

Posted on August 8, 2010
by

In Flex (as in Java, or even PHP) you can dynamically get references to a class from its name. Just to remind you, it’s that easy in PHP:

$className = 'User';
$myUser = new $className;

Not a lot more complicated in Java:

Class className = Class.forName("User");
Object myUser = className.newInstance();

The Flex way is as follows:

var className:Class = getDefinitionByName("package.User") as Class;
var user:Object = new className();

But despite PHP and Java, there is a little subtlety for Flex. You can encounter the following error when executing this code:

ReferenceError: Error #1065: Variable User is not defined

And it took some time for me to figure out what the problem was… After looking at the right speling of my class name and so worth, I figured out that the problem comes from the way that Flex compiles its code. Actually, Flex compiles its code so that if a class is not used, it will keep this class off the final compiled program. And even a

import package.User

won’t change a thing. The only way to get it done, is to put a reference to that class somewhere in your code, wherever … as long as it’s referenced somewhere, Flex will not forget the class at the compilation process. A simple and ugly way is to add a dummy reference to this class somewhere, like:

private var _dummyUser:User;

or shorter:

User;

and you’re done.

It has been already discussed on forums and blogs, but as I came across this I had to write an article about it 🙂

About the author

Cyril Mazur is a serial web entrepreneur with experience in various fields: online dating, forex & finance, blogging, online advertising... who enjoys building things that people like to use.

5 comments