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.

4

1 に答える 1

4

メソッドに必要な完全修飾名を付けてみてください。

Class.forName("com.package.where.class.exists.MyDataType").newInstance();
于 2013-03-11T05:04:08.347 に答える