Java ClassLoader mechanism and how to load an external class file (with code)

Source: Internet
Author: User
Tags bootstrap classes

The life cycle of the Java class

Life Cycle: Load (Loading)- Verification (verification)-"preparation (preparation)---" Analysis (Resolution)--" Initialize (initiation)---use (using)----unload (unloading). Where the verification of yellow---"Preparation---" Resolution is called the connection (linking).

As far as code execution is concerned:

1. Connect phase: Do not execute programmer code

2. Load phase: Can rewrite ClassLoader to execute our code

3. Post-connect stage: Code to execute the class

ClassLoader:

ClassLoader is a byte array for the class file, the primary method is findclass for finding the class.

Java7 has a way to quickly file program byte[]:

byte[] classbytes = null; Path Path;try {path = Paths.get (New URI ("File:///D:/MyScript/TestClassLoader.class")); classbytes = Files.readallbytes (path);

Each ClassLoader object has a field of type ClassLoader, which becomes the parent. When calling the LoadClass method of this class to load a class, the parent's ClassLoader is called first, and if he does not find it, the Findclass method of the class is called to find the class. (This way, the launcher$appclassloader of the application can also invoke the string class through Bootstrapclassloader).

Find the order of the classes, with the corresponding ClassLoader

The order in which the system looks for classes is:

1). Bootstrap classes : the runtime classes in  , internationalization classes in  i18n.jar , and others.

2) . Installed extensions : Classes in JAR files in the  lib/ext  directory of the JRE, and in the system-wide, platform-specific extension directory (such as  /usr /jdk/packages/lib/ext  on the Solaris? Operating System, but note the use of the This directory applies only to Java? 6 and later).

3). The class path: Classes, including classes in JAR files, on paths specified by the system propertyJava.class.path. If a JAR file on the class path have a manifest with theClass-Pathattribute, JAR files specified by theClass-Pathattribute'll be searched also. By default, thejava.class.pathProperty ' s value is., the current directory. You can change the value by using the-classpathor-CPcommand-line options, or setting theCLASSPATHenvironment variable. The command-line options override the setting of theCLASSPATHenvironment variable.

Chinese is:

1) Rt.jar etc (what is this jar?) You can see with the Java-verbose class name: Loaded java.io.File from C:\Program Files\java\jre1.8.0_31\lib\rt.jar, which is a string that is often called, Long class, which belongs to the SDK)(loaded with Bootstrapclassloader)

2) SDK Extension class, package named Javax (java and javax are Java API (application programming Interface) package, Java is core package, javax

(Loaded with Launcher$extclassloader )

3) system environment variable classpath path, current directory (or-classpath with command line)

(Loaded with Launcher$appclassloader )

However, my class files in D:\MyScript\TestClassLoader.class are not in the above three kinds.

2: Solution

1. Scenario: I want to load a class on the D disk, the path is: D:\MyScript\TestClassLoader.class, which is not in the above three cases.

By rewriting a classloader to load, but with ready-made urlclassloader we don't have to re-build the wheels.

Custom ClassLoader Code
public class Myclassloader extends classloader{@Overrideprotected class<?> findclass (String className) throws classnotfoundexception {byte[] classbytes = Null;//java 7 has the following APIs
<span style= "White-space:pre" ></span>path path;try {Path = Paths.get (New URI ("file:///D:/MyScript/ Testclassloader.class ")); classbytes = files.readallbytes (path);} catch (IOException | URISyntaxException e) {e.printstacktrace ();} Class class = DefineClass (Classbytes, 0, Classbytes.length); return class;}}

When used:
Class.forName ("Testclassloader", True, New Myclassloader ());

Use URLClassLoader to simplify
  ClassLoader Systemclassloader = Classloader.getsystemclassloader ();    This URL for a directory would be searched *recursively*    URL classes;try {classes = new URL ("file:///D:/MyScript/" );    ClassLoader custom =         new URLClassLoader (new url[] {classes}, Systemclassloader);    This class should is loaded from your directory    class<? > clazz = Custom.loadclass ("Testclassloader"); 
   
    method[] methods = Clazz.getdeclaredmethods ();    for (Method method:methods) {System.out.println (Method.getname ());}
   
The URL used by URLClassLoader can only accept directories and jar packages:

End:/Represents the directory under which the file is not/is the default jar package.

Code to paste a jar package:

Public URL FindResource (String name) {try {File file = new file (jarfile); String URL = File.tourl (). toString (); return new URL ("Jar:" +url+ "!/" +name);} catch (Exception e) {return null;}} <span style= "font-family:arial, Helvetica, Sans-serif; font-size:12px; Background-color:rgb (255, 255, 255); " ></span>

In addition, I use reflection to verify that the class is loaded successfully, and clazz.newinstance () can also generate related code.

Java ClassLoader mechanism and how to load an external class file (with code)

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.