Sunday, April 3, 2011

What does Class.fromName() not work for me?

Hello,

I'm trying to instantiate a class from variable, and written a test script. But, unfortunately, it isn't woriking. There is that script:

Object co1 = new CommandDownloadHttp();
Class cc1 = Class.forName("CommandDownloadHttp");
Object co = cc1.newInstance();

Unfortunately on second line it crashes with java.lang.ClassNotFoundException.

Can you please say me what I am doing wrong?

From stackoverflow
  • Is CommandDownloadHttp the full name of the class, i.e. it doesn't have a package? If it does have a package, include that:

    Class.forName("foo.bar.CommandDownloadHttp");
    

    (I assume there's a better reason for you doing this in your real code, btw - clearly in this case you don't actually need to fetch the class by reflection :)

    basszero : replace namespace w/ package (to be me java centric). I realize they're sorta the same concept.
    Arturas : Thank you! :) Yes, these lines is only example. In real life name will be constructed on execution.
    Jon Skeet : @basszero: Doh - thanks, corrected :)
  • Is your class in a package? And this package is imported? So it works in line 1. But you need the full qualified name in Class.forName("my.package.to.CommandDownloadHttp").

    Arturas : Thank you for answer. I didn't thought about package.

0 comments:

Post a Comment