Reproduced Dynamically loading jar files and class files in Java

Source: Internet
Author: User

Reprinted from http://blog.csdn.net/mousebaby808/article/details/31788325

An overview of servers such as Tomcat will load the jar files in the application's Lib directory and the class files under the classes directory at startup, as well as a framework like spring, which can scan and load the specified class file according to the specified path.  This technology enables a container to accommodate a wide variety of sub-applications. Java class because of the need to load and compile bytecode, dynamic loading class file is more troublesome, unlike the C-load dynamic link library as long as a file name can be done, but the JDK still provides a complete set of methods to dynamically load jar files and class files. Dynamically Loading JAR files [Java]View Plaincopy
  1. System Class Library Path
  2. File LibPath = new file (the path where the jar file is located);
  3. Get all. jar and. zip files
  4. file[] Jarfiles = libpath.listfiles (new FilenameFilter () {
  5. Public Boolean Accept (File dir, String name) {
  6. return Name.endswith (". Jar") | | name.endswith (". zip");
  7. }
  8. });
  9. if (jarfiles! = null) {
  10. //How to get the folder of the class from the URLClassLoader class
  11. //For jar files, it can be understood as a folder for storing class files.
  12. method = URLClassLoader. Class.getdeclaredmethod ("Addurl", URL.   Class);
  13. Boolean accessible = Method.isaccessible (); //Get access to methods
  14. try {
  15. if (accessible = = false) {
  16. Method.setaccessible (true); //Set access permissions for the method
  17. }
  18. //Get System class loader
  19. URLClassLoader ClassLoader = (urlclassloader) classloader.getsystemclassloader ();
  20. For (File file:jarfiles) {
  21. URL url = File.touri (). Tourl ();
  22. try {
  23. Method.invoke (ClassLoader, URL);
  24. Log.debug ("read jar file [name={}]", File.getname ());
  25. } catch (Exception e) {
  26. Log.error ("read jar file [name={}] Failed", File.getname ());
  27. }
  28. }
  29. } finally {
  30. Method.setaccessible (accessible);
  31. }
  32. }

Dynamically Loading class files [Java]View Plaincopy
  1. Set the root path of the class file
  2. For example, there is a test under/usr/java/classes. App class, The/usr/java/classes is the root path of this class, and the actual location of the. class file is/usr/java/classes/test/app.class
  3. File Clazzpath = new File (theroot path where the class file is located);
  4. Record the number of. class files Loaded
  5. int clazzcount = 0;
  6. if (clazzpath.exists () && clazzpath.isdirectory ()) {
  7. //Get path length
  8. int clazzpathlen = Clazzpath.getabsolutepath (). Length () + 1;
  9. stack<file> stack = new stack<> ();
  10. Stack.push (Clazzpath);
  11. //Traverse classpath
  12. While (stack.isempty () = = false) {
  13. File path = Stack.pop ();
  14. file[] Classfiles = path.listfiles (new FileFilter () {
  15. Public Boolean accept (File pathname) {
  16. return pathname.isdirectory () | | pathname.getname (). EndsWith (". Class");
  17. }
  18. });
  19. For (File subfile:classfiles) {
  20. if (subfile.isdirectory ()) {
  21. Stack.push (Subfile);
  22. } Else {
  23. if (clazzcount++ = = 0) {
  24. method = URLClassLoader. Class.getdeclaredmethod ("Addurl", URL.   Class);
  25. Boolean accessible = Method.isaccessible ();
  26. try {
  27. if (accessible = = false) {
  28. Method.setaccessible (true);
  29. }
  30. //Set class loader
  31. URLClassLoader ClassLoader = (urlclassloader) classloader.getsystemclassloader ();
  32. //Add the current classpath to the class loader
  33. Method.invoke (ClassLoader, Clazzpath.touri (). Tourl ());
  34. } finally {
  35. Method.setaccessible (accessible);
  36. }
  37. }
  38. //File name
  39. String className = Subfile.getabsolutepath ();
  40. ClassName = classname.substring (Clazzpathlen, Classname.length ()- 6);
  41. ClassName = Classname.replace (File.separatorchar, '. ');
  42. //Load class class
  43. Class.forName (ClassName);
  44. Log.debug ("Read application class file [class={}]", className);
  45. }
  46. }
  47. }
  48. }

Once you have completed these two steps, you can use Class.forName to load the Java classes contained in the jar or. class file.

Reproduced Dynamically loading jar files and class files in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.