Java Dynamic Loading jar and class file instance parsing, jarclass

Source: Internet
Author: User

Java Dynamic Loading jar and class file instance parsing, jarclass

This article focuses on the dynamic loading of jar and class files in Java. The details are as follows.

Class file loading in JAVA is dynamic. That is to say, it is loaded only when we use it. If it is not used, it will not load our class.

JAVA provides two dynamic mechanisms. The first is the implicit mechanism. The second is the display mechanism. As follows:

Two methods:

  • Implicit mechanism: new Object + static method of calling class
  • Explicit mechanism: loaded by the forName () method of java. lang. Class
    Loaded by the loadClass () method of java. lang. ClassLoader
1. Class. forName

The Class. forName () method has two forms:

  • public static Class forName(String className)
  • public static Class forName(String className, boolean initialize,ClassLoader loader)
Parameter description:
  • ClassName-fully qualified name of the required class (the package name must be included; otherwise, an error occurs !)
  • Initialize-whether class initialization is required (static code block initialization)
  • Loader-Class loader used to load classes

The forName () method that calls only one parameter is equivalent to Class. forName (className, true, loader ).

Both methods are connected to the native method forName0 ().

The forName () of the three parameters is called: forName0 (name, initialize, loader );

Whether new is used to instantiate a Class, or the Class. forName () method with only one parameter, the steps of loading Class + running static code blocks are hidden inside.

Use a Class with three parameters. for the forName () method, if the second parameter is false, the Class Loader only loads the class instead of initializing the static code block. Only when the class is instantiated, static code blocks are initialized only when the class is first instantiated.

2. java. lang. ClassLoader

ClassLoader is used to Load the Class. When a Class is loaded, all the classes referenced by this Class will be loaded, and this kind of loading is recursive. That is to say, if A references B and B references C, B is also loaded when A is loaded, and C is loaded when B is loaded. This recursion is performed until all required classes are loaded properly.

Package com. demo. test; import java. io. byteArrayOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. IOException; import java. lang. reflect. field; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method; import java.net. malformedURLException; import java.net. URL; import java.net. URLClassLoader; public class DynamicLoad Demo {enum FileType {JAR, CLASS, OTHER} static class MyClassLoader extends ClassLoader {public synchronized Class <?> LoadClass (String name, File file) throws FileNotFoundException {Class <?> Cls = findLoadedClass (name); if (cls! = Null) {return cls;} FileInputStream FCM = new FileInputStream (file); ByteArrayOutputStream baos = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int len; try {while (true) {len = Fi. read (buffer); if (len =-1) {break;} baos. write (buffer, 0, len);} // The flush operation of FileInputStream is empty, because flush is used to write the cached content into the entity (hard disk or network stream, this is not necessary here so it is null // baos. flush (); byte [] data = baos. toByteArray (); return defineClass (null, Data, 0, data. length);} catch (IOException e) {e. printStackTrace ();} finally {try {baos. close ();} catch (IOException e) {e. printStackTrace ();} try {FS. close ();} catch (IOException e) {e. printStackTrace () ;}} return null ;}} public static void main (String [] args) {String className = "com. demo. test. helloWorld "; String paths [] = {" HelloWorld. jar "," HelloWorld. class "}; for (String path: paths) {String lowe RPath = path. toLowerCase (); FileType fileType = FileType. OTHER; if (lowerPath. endsWith (". jar ") | lowerPath. endsWith (". zip ") {fileType = FileType. JAR;} else if (lowerPath. endsWith (". class ") {fileType = FileType. CLASS;} if (fileType = FileType. OTHER) {return;} File file = new File (path); if (! File. exists () {return;} try {URL url = file. toURI (). toURL (); System. out. println (url. toString (); Class <?> Cls = null; switch (fileType) {case JAR: URLClassLoader classLoader = new URLClassLoader (new URL [] {url}, Thread. currentThread (). getContextClassLoader (); cls = classLoader. loadClass (className); break; case CLASS: MyClassLoader myClassLoader = new MyClassLoader (); cls = myClassLoader. loadClass (className, file); break; default: break;} if (cls = null) {return ;}// instance variable Field field = cls. getDeclaredField (" Hello "); if (! Field. isAccessible () {field. setAccessible (true);} System. out. println (field. get (cls. newInstance (); // call the static Method without the parameter Method staticMethod = cls. getDeclaredMethod ("sayStaticHello", null); if (! StaticMethod. isAccessible () {staticMethod. setAccessible (true);} // if the return value of the function is void, nullstaticMethod is returned. invoke (cls, null); // Method with parameters for the instance method = cls. getDeclaredMethod ("say", String. class); if (! Method. isAccessible () {method. setAccessible (true);} Object ret = method. invoke (cls. newInstance (), "hello world"); System. out. println (ret);} catch (MalformedURLException e) {e. printStackTrace ();} catch (ClassNotFoundException e) {e. printStackTrace ();} catch (NoSuchMethodException e) {e. printStackTrace ();} catch (SecurityException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace ();} catch (IllegalArgumentException e) {e. printStackTrace ();} catch (InvocationTargetException e) {e. printStackTrace ();} catch (InstantiationException e) {e. printStackTrace ();} catch (NoSuchFieldException e) {e. printStackTrace ();} catch (FileNotFoundException e) {e. printStackTrace ();}}}}

Result:

Summary

The above is all the content about how to parse the jar and class file instances Dynamically Loaded by Java. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Related Article

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.