In a Java application I'm trying to create the instance of the class Class1 by using newInstance() method on the class. Class1 belongs to my project, but it also needs Class2 which is from another project and which is located in an external jar which I have added to the project and to the build path in Eclipse. Eclipse seems to find Class2 as it compiles the project without any problem, but when I try to get the instance of Class1 it throws a ClassNotFoundException about Class2.
This is how Class1 looks like:
import other.package.Class2;
public class Class1 implements Class1Interface{
//there's no explicit constructor
@Override
public void method1(String param){
System.out.println("Loading.....");
}
@Override
public void notifyChanges(String param) throws Exception{
Class2 class2 = Class2.getInstance(); //here it's used the Class2 from another jar
...
}
}
and this is how I try to get the instance of it:
String myParam = "blabla";
Class1Interface interf = "my.package.Class1";
try {
interf = (Class1Interface) Class.forName(interfazws).newInstance();
interf.method1(myParam);
} catch (InstantiationException e) {
handle(e);
} catch (IllegalAccessException e) {
handle(e);
} catch (ClassNotFoundException e) {
handle(e);
}
And when I execute that I get:
Caused by: org.springframework.scheduling.quartz.JobMethodInvocationFailedException: Invocation of method 'execute' on target class [class my.package.myJobJob] failed; nested exception is java.lang.NoClassDefFoundError: other/package/Class2
...
Caused by: java.lang.NoClassDefFoundError: other/package/Class2
...
Caused by: java.lang.ClassNotFoundException: other.package.Class2
Another thing to add about my project configuration is that under WEB-INF folder I have a folder called libs with some jars and I created another lib folder called libs_other_company and I have placed there the jar where Class2 is in. If I go to the java build path I can see the jar added in the libraries tab.
I am running the application in a Tomcat server directly from Eclipse (I'm not using anything like Ant or Maven).
How can it be possible that it finds the class at compile time but not at runtime? Any idea to make it works?
Thanks.
You confuse two separate things, compile time class path resolution and run time class path access.
When you compile your application, you need to have classes that your application uses/refers to in your development environment compile class path; if you don't (do that) then a compile time error will occur.
When you run your compiled application, you need to have all classes that your application uses/refers to in your JVM class path or included in your application package; if you don't (do that) then a run time error will occur.
You experience the second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With