Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load modules in Java

Tags:

java

module

jar

I'm building a server that loads modules. Each module is a .jar file. Inside the jar there's all the classes that the module needs. The server needs to read the jar, find the main class (it doesnt have the main method on it is just the class that makes the module work but not as a different program), build an object of that class and store it in a vector of modules so that it can acces to a specific module depending on the job to be done.

How can I do that?

As far as the server, it is listening and receiving request, but there's no modules to delegate the job to, since my vector of modules is empty.

like image 797
gerardorn Avatar asked Jun 14 '26 17:06

gerardorn


2 Answers

You should use Java's ServiceLoader class,

http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html

This requires your JAR has a provider configuration file in META-INF/services directory. This is the standard built-in way to load modules in Java. If you need more robust module loading, you might want look at OSGi.

like image 162
ZZ Coder Avatar answered Jun 16 '26 07:06

ZZ Coder


Here is a network class loader example from Sun. This should cover everything you need.

Try this syntax once you get the URL with you original URLClassLoader

JAR URL

The syntax of a JAR URL is:

jar:<url>!/{entry}

for example:

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

Accessing resources

final java.net.URL url = X.class.getResource ("/dir/image.png");
final ImageIcon icon = new ImageIcon (url);

Also look at this URL http://www.javaworld.com/javaworld/javatips/jw-javatip70.html

like image 23
Romain Hippeau Avatar answered Jun 16 '26 07:06

Romain Hippeau



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!