code_junkie

How should I load Jars dynamically at runtime?

Nov 10th, 2011
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.33 KB | None | 0 0
  1. URLClassLoader child = new URLClassLoader (myJar.toURL(), this.getClass().getClassLoader());
  2. Class classToLoad = Class.forName ("com.MyClass", true, child);
  3. Method method = classToLoad.getDeclaredMethod ("myMethod");
  4. Object instance = classToLoad.newInstance ();
  5. Object result = method.invoke (instance);
  6.  
  7. public class ClassPathHack {
  8. private static final Class[] parameters = new Class[] {URL.class};
  9.  
  10. public static void addFile(String s) throws IOException
  11. {
  12. File f = new File(s);
  13. addFile(f);
  14. }
  15.  
  16. public static void addFile(File f) throws IOException
  17. {
  18. //f.toURL is deprecated
  19. addURL(f.toURL());
  20. }
  21.  
  22. public static void addURL(URL u) throws IOException
  23. {
  24. URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
  25. Class sysclass = URLClassLoader.class;
  26.  
  27. try {
  28. Method method = sysclass.getDeclaredMethod("addURL", parameters);
  29. method.setAccessible(true);
  30. method.invoke(sysloader, new Object[] {u});
  31. } catch (Throwable t) {
  32. t.printStackTrace();
  33. throw new IOException("Error, could not add URL to system classloader");
  34. }
  35.  
  36. }
  37. }
  38.  
  39. JarClassLoader jcl = new JarClassLoader();
  40. jcl.add("myjar.jar"); //Load jar file
  41. jcl.add(new URL("http://myserver.com/myjar.jar")); //Load jar from a URL
  42. jcl.add(new FileInputStream("myotherjar.jar")); //Load jar file from stream
  43. jcl.add("myclassfolder/"); //Load class folder
  44. jcl.add("myjarlib/"); //Recursively load all jar files in the folder/sub-folder(s)
  45.  
  46. JclObjectFactory factory = JclObjectFactory.getInstance();
  47.  
  48. //Create object of loaded class
  49. Object obj = factory.create(jcl,"mypackage.MyClass");
  50.  
  51. /**************************************************************************************************
  52. * Copyright (c) 2004, Federal University of So Carlos *
  53. * *
  54. * All rights reserved. *
  55. * *
  56. * Redistribution and use in source and binary forms, with or without modification, are permitted *
  57. * provided that the following conditions are met: *
  58. * *
  59. * * Redistributions of source code must retain the above copyright notice, this list of *
  60. * conditions and the following disclaimer. *
  61. * * Redistributions in binary form must reproduce the above copyright notice, this list of *
  62. * * conditions and the following disclaimer in the documentation and/or other materials *
  63. * * provided with the distribution. *
  64. * * Neither the name of the Federal University of So Carlos nor the names of its *
  65. * * contributors may be used to endorse or promote products derived from this software *
  66. * * without specific prior written permission. *
  67. * *
  68. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
  69. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
  70. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
  71. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR *
  72. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
  73. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
  74. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *
  75. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
  76. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
  77. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
  78. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
  79. **************************************************************************************************/
  80. /*
  81. * Created on Oct 6, 2004
  82. */
  83. package tools;
  84.  
  85. import java.io.File;
  86. import java.io.IOException;
  87. import java.lang.reflect.Constructor;
  88. import java.lang.reflect.InvocationTargetException;
  89. import java.lang.reflect.Method;
  90. import java.net.URL;
  91. import java.net.URLClassLoader;
  92.  
  93. /**
  94. * Useful class for dynamically changing the classpath, adding classes during runtime.
  95. * @author unknown
  96. */
  97. public class ClasspathHacker {
  98. /**
  99. * Parameters of the method to add an URL to the System classes.
  100. */
  101. private static final Class<?>[] parameters = new Class[]{URL.class};
  102.  
  103. /**
  104. * Adds a file to the classpath.
  105. * @param s a String pointing to the file
  106. * @throws IOException
  107. */
  108. public static void addFile(String s) throws IOException {
  109. File f = new File(s);
  110. addFile(f);
  111. }//end method
  112.  
  113. /**
  114. * Adds a file to the classpath
  115. * @param f the file to be added
  116. * @throws IOException
  117. */
  118. public static void addFile(File f) throws IOException {
  119. addURL(f.toURI().toURL());
  120. }//end method
  121.  
  122. /**
  123. * Adds the content pointed by the URL to the classpath.
  124. * @param u the URL pointing to the content to be added
  125. * @throws IOException
  126. */
  127. public static void addURL(URL u) throws IOException {
  128. URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
  129. Class<?> sysclass = URLClassLoader.class;
  130. try {
  131. Method method = sysclass.getDeclaredMethod("addURL",parameters);
  132. method.setAccessible(true);
  133. method.invoke(sysloader,new Object[]{ u });
  134. } catch (Throwable t) {
  135. t.printStackTrace();
  136. throw new IOException("Error, could not add URL to system classloader");
  137. }//end try catch
  138. }//end method
  139.  
  140. public static void main(String args[]) throws IOException, SecurityException, ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{
  141. addFile("C:\dynamicloading.jar");
  142. Constructor<?> cs = ClassLoader.getSystemClassLoader().loadClass("test.DymamicLoadingTest").getConstructor(String.class);
  143. DymamicLoadingTest instance = (DymamicLoadingTest)cs.newInstance();
  144. instance.test();
  145.  
  146. }
  147. }
  148.  
  149. public void initialize(String libDir) throws Exception {
  150. File dependencyDirectory = new File(libDir);
  151. File[] files = dependencyDirectory.listFiles();
  152. ArrayList<URL> urls = new ArrayList<URL>();
  153. for (int i = 0; i < files.length; i++) {
  154. if (files[i].getName().endsWith(".jar")) {
  155. urls.add(files[i].toURL());
  156. //urls.add(files[i].toURI().toURL());
  157. }
  158. }
  159. classLoader = new JarFileClassLoader("Scheduler CL" + System.currentTimeMillis(),
  160. urls.toArray(new URL[urls.size()]),
  161. GFClassLoader.class.getClassLoader());
  162. }
Add Comment
Please, Sign In to add comment