Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassNotFoundException with Junit when using Class.forName(..).getInstance while new() works fine

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.

like image 723
broun Avatar asked Jan 22 '26 16:01

broun


1 Answers

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

Class.forName("com.package.where.class.exists.MyDataType").newInstance();
like image 61
Rahul Avatar answered Jan 25 '26 06:01

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!