Design Pattern
The solution build up from three part, the
Loader - loads and uses the jar files and Java class dynamically,
Communication interface(s) - defines the interface, what can be used to communicate the program and the dynamic library,
Dynamic libraries - the Loader loads and uses this libraries through the communication interface(s).
The loader, the communication interface(s) and the dynamic libraries must be separated in different projects, because
- Loader imports the communication interface(s)
- Dynamic libraries imports the communication interface(s)
- Loader can't know anything about the Dynamic libraries
- Dynamic libraries can't know anything about the Loader
Sample application
As usually, I made a sample application, what can help to you to understand my idea. The sample application is very similar now. The main program can be invocated with two parameter, the first is the name of the jar file to load, the second is the name of the class to load. The application loads the given jar file and class and say hello in two different language, depend on, which jar file is loaded.
Creating the communication interface(s)
There is only one communication interface, what defines only one simple method:
Creating a dynamic library
The sample dynamic library is as simple as the communication interface:
Creating the Loader
Sample application has a main class, what processes the program arguments:
and a class, where the codes are separated, that load the jar file and class dynamically:
Downloads
You can download sample projects here as NetBeans project.
3 comments:
Wow great solution...I was looking for it to develop some apps in J2ME :)
I searched for quite a few samples and solutions, tried a few, and yours was first to work like charm! Thanks.
This thing will work only within this classloader. If you decide to use your dynamically loaded class in some of other classes, you will get ClassNotFoundException.
Way to avoid it is add your library to system classloader.
Tricky thing here is to use reflection to make addURL method accessible and invoke it.
Like this:
Method method = URLClassLoader.class.getDeclaredMethod("addURL",new Class[]{URL.class});
method.setAccessible(true);
method.invoke((URLClassLoader) ClassLoader.getSystemClassLoader(), new Object[]{new URL("jar:file:/"+your_path)});
Post a Comment