3

Is there a way to load a java library (.jar file) at runtime, if it is not on the classpath?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Rogach
  • 26,050
  • 21
  • 93
  • 172
  • 1
    I have not dealt much with libraries*, but you might try using an URLClassLoader to get access to it. * BTW - by 'library' do you mean natives? – Andrew Thompson Nov 06 '10 at 05:48
  • No, I mean just a simple java library. (a .jar file) – Rogach Nov 06 '10 at 05:58
  • Yes, it's possible. I am voting to close this because google "java load jar dynamically" gave me a few decent SO answers and a number of other useful examples. –  Nov 06 '10 at 06:01
  • possible duplicate of [How should I load Jars dynamically at runtime?](http://stackoverflow.com/questions/60764/how-should-i-load-jars-dynamically-at-runtime) -- also see [How to load a jar file at runtime](http://stackoverflow.com/questions/194698/how-to-load-a-jar-file-at-runtime), etc. –  Nov 06 '10 at 06:01
  • @Andrew Thompson - your approach works, but it loads only one class at a time. Is there a way to load entire library? – Rogach Nov 06 '10 at 06:03
  • @Andrew Thompson - I found that all other classes are loaded automatically when I call them. Thanks. (If you'll post your answer, I'll select it) – Rogach Nov 06 '10 at 06:09
  • @pst - forgive me, haven't noticed that before. – Rogach Nov 06 '10 at 06:09

1 Answers1

6
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: How should I load Jars dynamically at runtime?

Community
  • 1
  • 1
zengr
  • 38,346
  • 37
  • 130
  • 192
  • `Important Comment From Source:` Using this approach you need to make sure you won't call this load method more than once for each class. Since you're creating a new class loader for every load operation, it can not know whether the class was already loaded previously. This can have bad consequences. For example singletons not working because the class was loaded several times and so the static fields exist several times – Chaitanya Mar 23 '20 at 00:04