Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an external jar file to the classpath dynamically at runtime? [duplicate]

Tags:

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, and then execute them as beans later (Spring Framework).

like image 276
EL Kamel Avatar asked Mar 04 '13 15:03

EL Kamel


People also ask

How do I include all JARs in a folder classpath?

In general, to include all of the JARs in a given directory, you can use the wildcard * (not *. jar ). The wildcard only matches JARs, not class files; to get all classes in a directory, just end the classpath entry at the directory name.


2 Answers

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

like image 111
Nikolay Kuznetsov Avatar answered Sep 19 '22 07:09

Nikolay Kuznetsov


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"); 
like image 34
Rahul Avatar answered Sep 22 '22 07:09

Rahul