views:

207

answers:

2

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?

+6  A: 

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 :)

Jon Skeet
replace namespace w/ package (to be me java centric). I realize they're sorta the same concept.
basszero
Thank you! :)Yes, these lines is only example. In real life name will be constructed on execution.
Arturas
@basszero: Doh - thanks, corrected :)
Jon Skeet
+2  A: 

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").

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