JAR插件的实现 [英] JAR plugins implementation

查看:171
本文介绍了JAR插件的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们有一个Groovy / Java应用程序,它应该使用一组类,在外部 *。jar -files中定义(假设它们位于主可执行文件jar )。因此,主类(让我们称之为 Main )应该加载 $ b>在运行时调用plugin.jar 文件,并在该jar中定义的类上调用一些实例方法(对于某些约定,假设该类的名称为jar - Plugin <

Main 类无法知道它拥有哪些插件,直到它运行。让我们抛弃 CLASSPATH java -jar 运行参数,只用代码来实现魔术。



那么,如何做到这一点以及如何创建 plugin.jar (在我的情况下使用Eclipse),以便正确加载?



PS:是的,我将groovy源文件编译为jar文件。但是我需要执行类加载并在运行中完全调用。

解决方案

秘密非常简单!



使用 URLClassLoader 可以做到这一点。 > Groovy 代码:

  ClassLoader loader = new URLClassLoader((URL [])[
new File (C:\\\\\ Users \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' b
$ b Class c = loader.loadClass(src.SomeClass1)

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

Java 一:

 文件文件=新文件(C:\\ Users \\\\\\\\\\\\\\' \\); 
URL [] url = new URL [] {file.toURI()。toURL()};
ClassLoader loader = new URLClassLoader(urls);
Class c = loader.loadClass(src.SomeClass1);
c.invokeMethod(main,new String [] {Hello,World!});


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.

解决方案

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!" });

这篇关于JAR插件的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆