【问题标题】:How to add an external jar file to the classpath dynamically at runtime? [duplicate]如何在运行时动态地将外部 jar 文件添加到类路径中? [复制]
【发布时间】:2013-02-18 17:44:24
【问题描述】:

我想使用 Java 代码动态地将 JAR 文件添加到我的项目的类路径中。如果可能的话,我想使用外部 jar 文件并加载它们的类,然后稍后将它们作为 bean 执行(Spring Framework)。

【问题讨论】:

    标签: java spring classpath


    【解决方案1】:
    URLClassLoader child = new URLClassLoader (myJar.toURL(), 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);
    

    来源:https://stackoverflow.com/a/60775/1360074

    【讨论】:

    【解决方案2】:

    您可以尝试这样的方法,但它要求您知道您的 JARs 的确切位置。

    URLClassLoader cl = URLClassLoader.newInstance(new URL[] {myJarFiles});
    Class myClass = cl.loadClass("com.mycomp.proj.myclass");
    Method printMeMethod = myClass.getMethod("printMe", new Class[] {String.class, String.class});
    Object myClassObj = myClass.newInstance();
    Object response = printMeMethod.invoke(myClassObj, "String1", "String2");
    

    【讨论】:

      猜你喜欢
      • 2016-02-14
      • 1970-01-01
      • 2013-08-27
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 2014-08-31
      相关资源
      最近更新 更多