简体   繁体   English

如何在运行时将新的Java文件加载到现有的Jar中?

[英]How to load a new java file into existing Jar during runtime?

I have a specific requirement where I need to load a class "abc" and invoke a method "xyz" during run time? 我有一个特殊的要求,我需要在运行时加载类“ abc”并调用方法“ xyz”? Is this possible? 这可能吗? Should the class file be present in a specific location? 类文件应该存在于特定位置吗?

I was trying the below code but am getting a ClassNotFoundException 我正在尝试下面的代码,但正在收到ClassNotFoundException

        File file = new File("location of the class file");
        URL url = file.toURI().toURL();
        URL[] urls = new URL[] {url};

        URLClassLoader myClass = new URLClassLoader(urls);
        Class<?> methodClass = myClass.loadClass("classname");
        Method method = methodClass.getDeclaredMethod(methodname);

Reflection allows you to create instances and call their methods by specifying the names of class and method. 反射允许您通过指定类和方法的名称来创建实例并调用其方法。 From your description it seems like you want this functionality. 从您的描述看来,您似乎需要此功能。

To make it easier to understand. 为了更容易理解。 You have the class Reflect: 您有班级Reflect:

package com.reflect;

public class Reflect {

  public void testMethod() { System.out.println("Test") }

}

And you have then this main class, where you call this method: 然后,您有了这个主类,在其中调用此方法:

package com.reflect.main;

import java.lang.reflect.Method;

public class ReflectApp {

  public static void main(String[] args) {

    Class noparams[] = {};

    try{
      //load the Reflect at runtime
      Class cls = Class.forName("com.reflect.Reflect");
      Object obj = cls.newInstance();

      //call the testMethod method
      Method method = cls.getDeclaredMethod("testMethod", noparams);
      method.invoke(obj, null);
    } catch(Exception ex) {
      ex.printStackTrace();
    }
  }
}

And here the link again to see the tutorial from where I put my own example. 这里的链接再次显示了我放置自己的示例的教程。

And in case you have to dynamically load the jar (in case it is not added to the classpath at compile time), you can do that by doing this: 并且如果必须动态加载jar(以防在编译时未将其添加到类路径中),可以通过执行以下操作:

// Getting the jar URL which contains target class
URL[] classLoaderUrls = new URL[]{new URL("file:///home/ashraf/Desktop/simple-bean-1.0.jar")};
URLClassLoader child = new URLClassLoader (classLoaderUrls, this.getClass().getClassLoader());
Class classToLoad = Class.forName ("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod ("myMethod");
Object instance = classToLoad.newInstance ();
Object result = method.invoke (instance);

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

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