3

I am getting ClassNotFoundException when running tests with junit:

I have a bunch of testcases that tests Class Main. The Main class has a method that takes in a string representing a datatype and internally builds an instance of the type using Class.forName( argument ).newInstance(). Now the methods itself works fine when i test manually. but while running test cases with junit i get ClassNotFoundException (in the method) for the passed in datatype.

Then i added a line: new MyDataType to the method being tested. Curiously the opration suceeds while the succeding line where i create an instance through Class.forName( MyDataType ).newInstance() fails.

Class Main{

public void someMethod( String dataType ){
new MyDataType();   // suceeds
Class.forName( dataType ).newInstance(); // got Exception when dataType = "MyDataType"
}
}

Why is this? When i googled i found a number of answers suggesting that MyDataType.class might not be in classpath. I dont think thats the case here since new MyDataType() runs fine.

My runtime and build time classpath includes the jar containing the required classes.

broun
  • 2,483
  • 5
  • 40
  • 55
  • Didn't see any issue of you code, how about clean you project and then run this test again, sometimes I got this kind of problem and fix it with this. – OQJF Mar 11 '13 at 05:17
  • tried it already, doesnt work !!! – broun Mar 11 '13 at 05:23
  • while I think the reason is that the Class.forName(), the reason is that the new MyDataType() just creates the instance while the Class.forName() must guarantee that the class has been loaded by the jvm or it will get the exception: classNotFound. – OQJF Mar 11 '13 at 06:00
  • Sorry I donot understand, if the class wasnt loaded by jvm instance creation with new() will also cause the exception wouldnt it? – broun Mar 11 '13 at 06:40
  • please follow this link: http://stackoverflow.com/questions/2092659/what-is-difference-between-class-forname-and-class-forname-newinstance.to find more – OQJF Mar 11 '13 at 07:25
  • Post your directory structure plz, especially for your `Main` class and your `MyDataType` class. If the classpath is right, the most possible thing is that you wrote a wrong class name. – Dante WWWW Mar 11 '13 at 10:08

1 Answers1

4

Try giving the full qualified name, which is needed by the method:

Class.forName("com.package.where.class.exists.MyDataType").newInstance();
Markus
  • 2,071
  • 4
  • 22
  • 44
Rahul
  • 44,383
  • 11
  • 84
  • 103
  • 1
    it did not work either. got exception saying could not find file/directory – broun Mar 11 '13 at 05:16
  • This works fine, sorry for the previus comment but why is full class name required and not just simple class name. is there a way to dynamically load a class with simple name ? – broun Mar 11 '13 at 19:02