Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassNotFoundException while using Class.forName to load a class dynamically

 
sreenivas vemula
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code is throwing ClassNotFoundException:

public Object getPropertyObj(String key) throws Exception {
Class cls = Class.forName(key);
return cls.newInstance();
}

Please suggest...

Thanks in advance.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The key variable contains the name of a class that is not on your classpath.
The first thing you should do is print out the value of key to make sure it contains what you think it contains.
 
sreenivas vemula
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
could you please correct me if I am adding a class to a classpath in a right way or not?

system --> advanced --> environmental variables --> classpath

under this I am adding the location of a file

my jave file is located under the directory say D:\proj\pck

then what should be the variable value that needs to be added to classpath variable name.


 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're much better off not setting the environment classpath at all, and setting the classpath in the java command line using the -cp option.

Is the class in a package? The classpath ought to contain the root of the package structure. So if, for instance, the class file is in D:\proj\pck, but it's in the package pck, then the classpath ought to contain D:\proj
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sreenivas vemula wrote:my jave file is located under the directory say D:\proj\pck

It's the location of the class file that is important, not the java file
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic