Classloader in Java

Source: Internet
Author: User
Classloader in Java
Write Java reflection and classloader in a simple way. It is interesting to use reflection before. Here is a simple summary to prepare for learning spring3.x. 1. Java reflection in JDBC, we usually first load the bytecode of the driver class of a specific database based on a string, as follows:
Class.forName("com.mysql.jdbc.Driver");Class.forName("oracle.jdbc.OracleDriver");Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

Classloader is actually used here:

// ClassLoader loader = ReflectTest.class.getClassLoader();ClassLoader loader = Thread.currentThread().getContextClassLoader();

Then you can perform the following operations:

// Obtain the declared Constructor (any permission modifier). This parameter is constructed by default without any parameters. To generate a parameter, you only need to input the corresponding parameter type class object constructor cons = clazz. getdeclaredconstructor (); // create the object car = (CAR) cons. newinstance (); // obtain the setbrand method setbrand = clazz based on the type of the input method parameter. getmethod ("setbrand", String. class); // callback method setbrand. invoke (car, "Red Flag ca72"); // Similarly, method setmaxspeed = clazz. getmethod ("setmaxspeed", Int. class); setmaxspeed. invoke (cars, 200 );

The problem arises. If we obtain the method or attribute of a class that is not public, an exception will be thrown if we access a non-public method or attribute without setting: Java. Lang. illegalaccessexception

We only need to add a line of code: setaccessible (true). This is usually not done. This can be solved with special requirements;
// Obtain the private attribute field color== clazz. getdeclaredfield ("color"); // you can specify the value of the parameter to access colorclassification. setaccessible (true); color=. set (pcar, "Red"); // method to obtain the private declaration method drivemtd = clazz. getdeclaredmethod ("Drive"); // you can access drivemtd. setaccessible (true); drivemtd. invoke (pcar, (object []) null );

Java reflection mechanisms are widely used in many frameworks and are rarely used in development. If you need to write some frameworks by yourself, the underlying layer cannot escape the use of Java reflection, the reflect package in JDK provides these classes and interfaces. For details, you can find them in the API.
Classloader: the working mechanism of classloader is an important Java Runtime Environment component. It is responsible for searching and loading class bytecode files at runtime. Class loading is performed by classloader and its sub-classes. The JVM will generate three classloader at runtime, Which is exactly two. Because the root loader is not a subclass of classloader, it is written in C ++, so it cannot be seen in Java, look at a small program:

Public class classloadertest {public static void main (string [] ARGs) {// Class Loader for obtaining the context of the current thread classloader loader = thread. currentthread (). getcontextclassloader (); // classloader loader = classloadertest. class. getclassloader (); system. out. println ("Current Loader:" + loader); // The current class loader System. out. println ("parent Loader:" + loader. getparent (); // The parent loader System. out. println ("grandparent Loader:" + loader. getparent (). getparent ());}}
The output result is:
Current loader:sun.misc.Launcher$AppClassLoader@6b97fdParent loader:sun.misc.Launcher$ExtClassLoader@1c78e57Grandparent loader:null

@ Classloader: Root loader, responsible for loading the core class library of JRE, such as charsets under the JRE target. jar and RT. jar, etc., cannot be accessed in Java, cannot obtain its handle, return null.

@ Extclassloader: a subclass of classloader. It is responsible for loading the jar class package in the ext directory of the JRE extension. @ Appclassloader: a subclass of extclassloader. It is responsible for loading class packages under the classpath path.

Overall entrusting mechanism: Overall responsibility:When a classloader loads a class, unless explicitly specified to use another classloader, the class lock dependency and referenced classes are also loaded by this classloader.Delegation mechanism:First, entrust the parent loader to find the target. Only when the target class cannot be found can the parent loader find and load the target class from its own class path. This avoids a security risk, for example, if I accidentally write a string (written in the initial stage), the delegate mechanism or the delegate parent loader loads the string class, this will not load the string class I wrote.

Add several frequently used classloader interface methods:

Class loadclass (string name)The name parameter specifies the name of the class to be loaded by the class loader. A fully qualified class name must be used, for example, Com. baobaotao. Beans. Car.

This method has an overloaded method loadclass (stringname, Boolean resolve). The resolve parameter tells the Class Loader whether to parse the class. Before initializing a class, you should consider class resolution,

However, not all classes need to be parsed. If the JVM only needs to know whether the class exists or find out the super class of the class, it does not need to be parsed.

Class findsystemclass (string name)Load the class file from the local file system. If the class file does not exist in the local file system, a classnotfoundexception exception is thrown. This method is the default loader system used by JVM.

Class findloadedclass (string name)Call this method to check whether the classloader has loaded a class. If it has been loaded, the Java. Lang. Class Object is returned; otherwise, null is returned. If an existing class is forcibly loaded, a link error is thrown.

Classloadergetparent ()Obtain the parent loader of the Class Loader. Apart from the root loader, all class loaders have only one parent loader. The parent loader of extclassloader is the root loader, because the root loader is not written in Java, it cannot be obtained and null is returned.

The following figure describes the relationship between the class loader and objects:
Object. getclass () Class --- obtains the class bytecode class from the instance object. getclassloader () classloader ---- class bytecode object to obtain Class Loader classloader. loaderclass (string classname) Class ---- the Class Loader reprints a specific class

 

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.