JAR plugins implementation

2019-05-14 19:49发布

问题:

Let us have a Groovy/Java application that should use a set of classes, defined in external *.jar-files (suppose they are located near the main executable jar).

So, the main class (let us call it Main) should load plugin.jar file at runtime and call some instance method on the class, defined in that jar (for some convention, suppose the class has the name as its jar - Plugin in our case).

The Main class could not know which plugins it has until it is runned. Let's throw away the CLASSPATH and java -jar run arguments and just do the magic with code only.

So, how this could be done and how the plugin.jar should be created (using Eclipse in my case) in order to be correctly loaded?

PS: yeah, i do compile my groovy sources into jar file. But i need to perform class loading and invoke exactly on-the-fly.

回答1:

The secret was really simple!

Using URLClassLoader does the trick.

So, Groovy code:

ClassLoader loader = new URLClassLoader((URL[]) [
    new File("C:\\Users\\errorist\\workspace\\javatest1\\bin\\").toURI().toURL()
])

Class c = loader.loadClass("src.SomeClass1")

c.invokeMethod("main", (String[]) ["Hello", "World"])

And the Java one:

File file = new File("C:\\Users\\errorist\\workspace\\javatest1\\bin\\");
URL[] urls = new URL[] { file.toURI().toURL() };
ClassLoader loader = new URLClassLoader(urls);
Class c = loader.loadClass("src.SomeClass1");
c.invokeMethod("main", new String[] { "Hello", "World!" });


回答2:

The OSGi framework supports dynamic loading of plug-ins. There are multiple implementations, including Equinox, which underpins Eclipse itself.