简体   繁体   English

使用 URLClassLoader 动态加载 JAR?

[英]Dynamically load a JAR using URLClassLoader?

I have a program which needs to be able to dynamically load JARs at runtime - after looking around I beleive this uses URLClassLoader, but I'm not sure how to get it to work.我有一个程序需要能够在运行时动态加载 JAR - 环顾四周后,我相信它使用了 URLClassLoader,但我不确定如何让它工作。 The JAR "openup.jar" is in the same directory as the program. JAR“openup.jar”与程序位于同一目录中。

Ideally I would like to be able to load this JAR without having to specify each individual class inside it.理想情况下,我希望能够加载这个 JAR,而不必在其中指定每个单独的类。

What I successfully used: 我成功使用了什么:

@SuppressWarnings("unchecked")
public void addURL(URL u) throws IOException {
    URLClassLoader sysLoader = (URLClassLoader) ThisClass.class.getClassLoader();
    URL urls[] = sysLoader.getURLs();
    for (int i = 0; i < urls.length; i++) {
        if (urls[i].toString().equalsIgnoreCase(u.toString())) {
            return;
        }
    }
    Class sysclass = URLClassLoader.class;
    try {
        Method method = sysclass.getDeclaredMethod("addURL", parameters);
        method.setAccessible(true);
        method.invoke(sysLoader, new Object[] { u });
    } catch (Throwable t) {
        throw new IOException("Error, could not add URL to system classloader");
    }
}

An almost identical solution is indeed presented in How should I load Jars dynamically at runtime? 在运行时如何动态加载Jars中确实提供了几乎相同的解决方案

Here I am explaining the full process of creating a jar and then loading a jar dynamically in another project:这里我解释一下创建jar然后在另一个项目中动态加载jar的全过程:

Steps to create jar:创建jar的步骤:

  1. Create a new Project in any IDE(Eclipse).在任何 IDE(Eclipse)中创建一个新项目。
  2. Add a Sample class in packages(in my case MyClass).在包中添加一个 Sample 类(在我的例子中是 MyClass)。
  3. Do right-click on the project and then export as jar and give a local path of system location where the jar wants to keep(right-click -> Export -> choose java/jar file -> next ->give path -> finish).右键单击项目,然后导出为 jar 并给出 jar 想要保留的系统位置的本地路径(右键单击 -> 导出 -> 选择 java/jar 文件 -> 下一步 -> 给出路径 -> 完成)。
  4. Then jar will be available at given location.然后 jar 将在给定位置可用。

package newJar.com.example;包 newJar.com.example;

public class MyClass {公共类 MyClass {

public MyClass() {
    // TODO Auto-generated constructor stub
}

public void helloWorld() {
    System.out.println("Hello from the helloWorld");
}

} }

Steps to load the jar dynamically:动态加载jar的步骤:

  1. Create a new project and add below code:创建一个新项目并添加以下代码:

    public class CustomClass {公共类自定义类{

    public CustomClass() { // TODO Auto-generated constructor stub } public CustomClass() { // TODO 自动生成的构造函数存根 }

    public void getCall(File myJar) {公共无效getCall(文件myJar){

     try { URLClassLoader loader = new URLClassLoader(new URL[] { myJar.toURI().toURL() }, CustomClass.class.getClass().getClassLoader()); Class classToLoad = Class.forName("newJar.com.example.MyClass", true, loader); System.out.println(classToLoad); Method method = classToLoad.getDeclaredMethod("helloWorld"); Object instance = classToLoad.newInstance(); Object result = method.invoke(instance); } catch (MalformedURLException | ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); }

    } }

    public static void main(String[] args) { // TODO Auto-generated method stub public static void main(String[] args) { // TODO 自动生成的方法存根

     File myJar = new File("Path of your jar ");//"D:\\\\ECLIPSE\\\\myjar.jar" CustomClass cls = new CustomClass(); cls.getCall(myJar);

    } }

} }

This is how it can make use of the jar and if the jar is on the server then can give the server path instead of the local path.这就是它如何使用 jar 的方式,如果 jar 在服务器上,则可以提供服务器路径而不是本地路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM