How To add an External jar File to the ClassPath Dynamically at runtime?

后端 未结 2 642
逝去的感伤
逝去的感伤 2021-02-02 11:57

I want to add a jar File to my project\'s classpath dynamically using java code if it is possible , I want to use external jar files and load their classes the execute them as B

相关标签:
2条回答
  • 2021-02-02 12:44

    You can try something like this, but it requires you to know, where exactly your JARs are located.

    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");
    
    0 讨论(0)
  • 2021-02-02 12:47
    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);
    

    Source: https://stackoverflow.com/a/60775/1360074

    0 讨论(0)
提交回复
热议问题