I have a project that will be reasonably large, so it would be very interesting to modularize, I know, there is OSGi, but I found it very complex and I had difficulty adapting my application, the impression I had is that it will complicate more than facilitating the maintenance, is too much cage simply to use a class that is in a separate jar through an interface, so I am thinking of doing through ClassLoader, the framework I think is the following
Core Project
package core;
public interface IModulo {
<T> T getString();
}
Sample Module Project
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 dependency, ie the IModulo interface is already in the classpath, if I run through a simple main class, it works, but at least Tomcat does not, 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