Skip to content

Loading a dinamic Library

Note

I’m not loading a .jar library, I’m only loading a .class, which implements my library functions. To test this code you must have in the directory D:\LoadLibrary a TestHelloWorld.class and the interface TestString WITH THE SAME package that you have in the main code. It means that if your TestString in your main code is com.haduart.TestString you must put your TestString.class in the D:\LoadLibrary\com\haduart\TestString.class.

  1. /**
  2. * In the D:/LoadLibrary we must have .class and the same interface (TestString) with the same pacakge as the
  3. * main program.
  4. */
  5. URL urlToJar = new URL(“file://D:/LoadLibrary/”);
  6. URLClassLoader cl = new URLClassLoader(new URL[] { urlToJar });
  7. System.out.println(“loading…”);
  8. Class c2 = cl.loadClass(“TestHelloWorld”);
  9. System.out.println(“loaded!”);
  10. Object nouObject = c2.newInstance();
  11. TestString ts = (TestString) cons.newInstance(args);
  12. /**
  13. * Now we can use the “ts” object as a normal TestString interface. No matter which is the implementation that is begin it.
  14. */
  15. System.out.println(“S1: “ + ts.printS1());
  16. System.out.println(“S2: “ + ts.printS2());