2
I have a project that will be fairly large, so it would be very interesting to modularize, I know, there is Osgi, but I found it very complex and had difficulty adapting my application, the impression I had is that it will complicate more than facilitating maintenance,is too bold simply to use a class that is in a separate jar through an interface, so I’m thinking of doing through Classloader, the structure I think is the following
Core Project
package core;
public interface IModulo {
<T> T getString();
}
Example Project Module
package modulo1;
import core.IModulo;
public class Teste implements IModulo{
public <T> T getString() {
return (T) "Hello";
}
}
Main project, where the modules will be "installed", this main project already has the Core project as a dependency, that is, the Imodulo interface is already in the classpath, if I run through a simple main class, it works, but by Tomcat no, see the code snippet
import core.IModulo;
public class Main {
public static void main(String[] args) {
try {
String jarDoModulo = "C:\\modulo1.jar";
File file = new File(jarDoModulo);
URL url;
url = file.toURL();
URL[] urls = new URL[] { url };
ClassLoader cl = new URLClassLoader(urls);
Class<IModulo> cls = (Class<IModulo>) cl.loadClass("modulo1.Teste");
IModulo modulo1 = cls.newInstance();
System.out.println(modulo1.getString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The error that appears is
Caused by: java.lang.ClassNotFoundException: core.IModulo
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 60 more
Hello Rodrigo, I changed the tag [tag:java-ee] by [tag:Tomcat] to try to help you attract more answers. Each container has its feature configuration specifics and Classloaders. Besides Tomcat is a special case that is not even a Java EE application server, it is just a container Servlet / JSP.
– Anthony Accioly