How to load modules in Java
I am creating a server that loads modules. Each module is a file .jar
. Inside the jar there are all the classes that the module needs. The server needs to read the jar, find the main class (it doesn't have a main method, it's just a class that makes the module work, but not like another program), build an object of that class and store it in a module vector so that it can connect to a specific module in depending on the task being performed.
How can i do this?
As far as the server is concerned, this is a listen and receive request, but there are no modules to delegate the job as my module vector is empty.
a source to share
You have to use Java ServiceLoader class,
http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html
This requires your JAR to have a vendor config file in the META-INF / services directory. This is the standard built-in way of loading modules in Java. If you want more reliable module loading, you might need to look at OSGi.
a source to share
An example of a network class loader from Sun. This should cover everything you need.
Try this syntax as soon as you get the url with the original URLClassLoader
JAR URL
JAR URL syntax:
jar:<url>!/{entry}
eg:
jar:http://www.foo.com/bar/baz.jar!/COM/foo/Quux.class
jar:file:/export/home/faculty/stansif/public_html/java/applets/image/view.jar!/image.gif
Access to resources
final java.net.URL url = X.class.getResource ("/dir/image.png");
final ImageIcon icon = new ImageIcon (url);
Also take a look at this url http://www.javaworld.com/javaworld/javatips/jw-javatip70.html
a source to share
You should look at the existing frameworks, including the lightweight OSGi container. However, the general approach that should be taken is to create a classloader for each module and call into each module using Reflection or the regular API - Runnable
both of Callable
which are good candidates.
a source to share