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.

4 comments

  1. Andre Uschmann
    on February 1, 2012
    Hey man,

    you just saved my life. I had this reference error while working on a flex-mobile project.
    For some Reason Flex did not include the labelitemrenderer into my app.

    After declaring a dummy reference everything wents fine.
    Thanks alot i love you guy.

    greetz from germany

    Andre
  2. Cyril
    on February 1, 2012
    Glad to see my post helped you ;-)
  3. Alex H
    on February 20, 2012
    Thanks a lot - I'd just wasted an hour or so trying to figure out why getDefinitionByName wasn't working for me before googling it and finding your post with the answer. Cheers!
  4. michael corbridge
    on October 4, 2013
    thank you ...

    I think I remember running into this problem years ago - so thanks for jogging my memory.

Leave a Reply