23

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).

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
EL Kamel
  • 824
  • 2
  • 12
  • 27

2 Answers2

16
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

Community
  • 1
  • 1
Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101
  • You shouldn't really use `Class#newInstance()` because it can introduce an undeclared checked exception http://docs.oracle.com/javase/tutorial/reflect/member/ctorTrouble.html it's better to use `Class#getConstructor()#newInstance()` – Philippe Marschall Mar 04 '13 at 15:41
  • Thank NiKolay Kusznetov , I found the Answer int Source discussion :) – EL Kamel Mar 04 '13 at 15:50
3

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");
Rahul
  • 44,383
  • 11
  • 84
  • 103