Question

I'm trying to instantiate a class from variable, and wrote some test code. But, unfortunately, it isn't working. Here is the code:

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 tell me what I am doing wrong?

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top