Urlclassloader loads the class to the current Thread class loader [ZT]

Source: Internet
Author: User
We know that Java uses classloader to load classes into the memory, and in the same application, there can be many classloader, through the delegate mechanism, the load task is passed to the upper-level loader, and so on until the class loader is started (there is no parent class loader ). If the class loader can load this class, it will first load it. If not, pass it down. When the parent class is null, the built-in JVM class (called Bootstrap Class Loader) will act as the parent class. Think about the increasing use of XML files for configuration files, descriptors, and deployment operators. In fact, the configuration information described in the XML document will eventually become a Java class, and the base is completed through classloader. Urlclassloader is a subclass of classloader. It is used to load classes and resources from the search path pointing to the URLs of jar files and directories. In other words, you can use urlclassloader to load the class in the specified jar to the memory.

The following is an example. In this example, we need to use urlclassloader to load the jar and run a method of the class.

First, we define an interface so that all classes that inherit it must implement the Action method, as shown below:

Public interface actioninterface {
Public String action ();
}
Package it into the testinterface. jar file.

Next, create a project and introduce the testinterface. jar package. Create the testaction class to implement the actioninterface interface. As follows:

Public class testaction implements actioninterface {
Public String action (){
Return "com. mxjava. testaction. Action ";
}
}

Package it as test. jar and put it in the C root directory. The following is how to use urlclassloader to load and run the Action Method of testaction, and print the returned value on the console.

Create a project and introduce the testinterface. jar package. Create an executable class (main method) and add the following code to it:

URL url = new URL ("file: C:/test. Jar ");

// (You also need to add and throw an exception)
Urlclassloader myclassloader = new urlclassloader (new URL [] {URL });

// Use urlclassloader myclassloader = new urlclassloader (new URL [] {URL}, thread. currentthread (). getcontextclassloader () in the web program ());

Class myclass = myclassloader. loadclass ("com. mxjava. testaction ");
Actioninterface action = (actioninterface) myclass. newinstance ();
System. Out. println (action. Action ());
In the preceding example, the c: \ test. jar package, where COM. mxjava. load the testaction class into the memory, forcibly convert it to the actioninterface type in the testinterface package, call its action method, and print it to the console.

After the program is executed, print the desired content on the console as scheduled. However, things are not that simple. When we move the code to a web application, an exception will be thrown. Originally, Java provided three classloader options:
1. system class loader or application Class Loader)
2. Current Class Loader
3. Current Thread class loader

In the above example, we use the javac command to run the program. At this time, we use the system classloader ). This class loader handles class loading in classpath and can be called through classloader. getsystemclassloader () method. All static getsystemxxx () methods under classloader are defined through this method. In the code, you should call this method as little as possible and use other class loaders as proxies. Otherwise, the code can only work in simple command line applications. In Web applications, the server uses classloader to load classes. Due to different classloader types, the JVM determines that classes are not of the same type during forced transformation. (In java, a class uses its fully-matched Class Name (fully qualified class name) as its identifier. Here, the fully-matched class name includes the package name and class name. However, in JVM, a class uses its full name and an instance that loads classloader as a unique identifier. Therefore, if a package named PG contains a class named Cl that is loaded by an instance kl1 of the Class Loader klassloader, that is, c1.class is expressed as (CL, PG, kl1) in JVM ). This means that the instances (CL, PG, kl1) and (CL, PG, kl2) of the two class loaders are different, so the classes loaded by them are completely different, .) To make the program run correctly, we must first solve the problem of how to keep the classes loaded by urlclassloader in the same class as the current classloader. The solution is simple. Use the third classloader provided by Java-the current Thread class loader. The jdk api documentation shows that urlclassloader provides three construction methods:

// Use the default delegate parent classloader to construct a new urlclassloader for the specified URL.
Urlclassloader (URL [] URLs)
// Construct a new urlclassloader for the given URL.
Urlclassloader (URL [] URLs, classloader parent)
// Create a new urlclassloader for the specified URL, parent class loader, and urlstreamhandlerfactory.
Urlclassloader (URL [] URLs, classloader parent, urlstreamhandlerfactory factory)
The next step is to place the current Thread class loader when constructing the urlclassloader. As follows:

Urlclassloader myclassloader = new urlclassloader (new URL [] {URL}, thread. currentthread (). getcontextclassloader ());
Summary:
Java uses classloader to load classes to the memory. classloader is written in Java, so we can extend our classloader. You can use urlclassloader to load classes in the specified jar package to the memory. When using urlclassloader to load jar on the life line, the system class loader is used to load the class. Therefore, an error occurs in the Web environment. This is because a class in JVM uses its full name and an instance loaded with classloader as a unique identifier. We only need to use the second construction method of urlclassloader and pass it into the current Thread class loader.

Http://www.mxjava.com/blog/article.asp? Id = 188

 

My sample program:

Import java. Io. ioexception;
Import java. Io. printwriter;

Import javax. servlet. servletexception;
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;

Import PK. CS;

Import java.net. url;
Import java.net. urlclassloader;

Import evaluated. pfinterface;

Public Class A extends httpservlet {

/**
* The doget method of the servlet. <br>
*
* This method is called when a form has its tag Value Method equals to get.
*
* @ Param request the request send by the client to the server
* @ Param response the response send by the server to the client
* @ Throws servletexception if an error occurred
* @ Throws ioexception if an error occurred
*/
Public void doget (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {

Response. setcontenttype ("text/html ");
Printwriter out = response. getwriter ();



Double [] A = {2, 3 };
Int [] B = {1, 3 };
Double F = 5;
Int x = 9;

// Implementation package of methods in the interface
// URL url = new URL ("file: D:/Eclipse/workspace/pfinterfacefun. Jar ");
URL url = new URL ("file: D:/myeclipse 5.5.1 Ga/workspace/pfinterfacefun. Jar ");
// Urlclassloader myclassloader = new urlclassloader (new URL [] {URL });

Urlclassloader myclassloader = new urlclassloader (new URL [] {URL}, thread. currentthread (). getcontextclassloader ());

Class myclass = NULL;
Try {
Myclass = myclassloader. loadclass ("evaluated. pfinterfacefun ");
} Catch (classnotfoundexception E1 ){
// Todo auto-generated Catch Block
E1.printstacktrace ();
}


Pfinterface action = NULL;
Try {
Action = (pfinterface) myclass. newinstance ();
} Catch (instantiationexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (illegalaccessexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}

Out. print (action. getpf (A, B, F, X, X, f, x, x) + "-- urlclassloader result <br/>"); // call the interface function

 






Int I, J, K;
CS go = new CS ();

I = 123;
Out. Print ("the result is" + go. Fun (I) + "<br/> ");

Out
. Println ("<! Doctype HTML public \ "-// W3C // dtd html 4.01 transitional // en \"> ");
Out. println ("<HTML> ");
Out. println ("Out. println ("<body> ");
Out. Print ("this is ");
Out. Print (this. getclass ());
Out. println (", using the get method ");
Out. println ("</body> ");
Out. println ("Out. Flush ();
Out. Close ();
}
}

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.