Reputation: 21
I have a web application program which runs different instance of a interface (execute) depending on a string which is retrieved from the user:
public interface IExecute{
public void run();
}
public class XExecute implements IExecute {...}
public class YExecute implements IExecute {...}
public class Handler{
public static run(String executorName){
IExecute executor = getImple(executorName);
executor.run();
}
private static IExecute getImple(String executorName){
return (IExecute) Class.forName(executorName+"Execute").getConstructor().newInstance();
}
}
This program works correctly. But I occasionally need to add a new implementation of IExecute while the application is running. I do not want to stop/start the application (for compiling the new source) each time I write a new implementation because a lot of operations are running in the application. In fact I want a solution to limit all the process to just compiling the new java file when application is running. Any other solution even complex ones can be helpful a lot.
Upvotes: 2
Views: 77
Reputation: 21
Using URLClassLoader and ServiceLoader works great:
Now I can create jar files in which there are some implementations of IExecute. Instruction to do so: https://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html.
The application loads those jar files by the class loader. Then a service loader loads all the implementations. Afterwards by iterating on the implementations it find one name of which matches the specified name. Finally it calls the run method.
File jarsDirectory = new File(path);
File[] files = jarsDirectory.listFiles();
URL[] urls = new URL[files.length];
for(int i=0;i<files.length;i++)
urls[i] = files[i].toURI().toURL();
URLClassLoader classLoader = new URLClassLoader(urls,ClassLoader.getSystemClassLoader());
ServiceLoader<IExecute> services = ServiceLoader.load(IExecute.class, classLoader);
Iterator<IExecute> itrs = services.iterator();
while(itrs.hasNext()){
IExecute execute = itrs.next();
if(execute.getClass().getSimpleName().equals("XExecute"))
execute.run();
}
Upvotes: 0
Reputation: 2652
Could you have a look at OSGI framework: https://www.osgi.org/developer/architecture/
It is said that:
The OSGi technology is a set of specifications that define a dynamic component system for Java. These specifications enable a development model where applications are (dynamically) composed of many different (reusable) components.
Dynamic software update is very meaningful for the downtime-critical applications to reduce the downtime during the software evolution phase. Nowadays more and more complicated applications are developed on the OSGi platform. Eclipse, WebSphere Liberty, JBoss, Glassfish all are using OSGI framework.
The service dynamics were added so we could install and uninstall bundles on the fly while the other bundles could adapt.
Hope, it helps.
Upvotes: 1