Easy to play classpath_jsp programming Java configuration

Source: Internet
Author: User

In the process of dealing with Java Classpath (CLASSPATH), developers occasionally get into trouble. This is because the class loader actually loads which class is sometimes not obvious, especially when the application's classpath contains a large number of classes and directories. This article provides a tool that can display the absolute pathname of the loaded class file.

   First, Classpath Foundation

The Java Virtual machine (JVM) loads the classes used by the application with the class loader, and specifies which classes are to be determined according to the requirements of the time. The CLASSPATH environment variable tells the class loader where to look for classes and user-defined classes provided by third parties. Alternatively, you can use the JVM command-line argument-classpath to specify the classpath for the application, and the classpath specified in-classpath overrides the value specified in the CLASSPATH environment variable.

The contents of the classpath can be: The directory of the file (containing the classes that are not in the package), the root of the package (which contains the packaged class), and the file containing the class (such as a. zip file or a. jar file). On Unix family systems, the items of the classpath are separated by colons, which are separated by semicolons on the MS Windows system.

Class loaders are organized in the form of a delegate hierarchy, and each class loader has a parent class loader. When a class loader is asked to load a class, it will first delegate the request to its parent loader before trying to find the class itself. The System class loader, the default class loader provided by the JDK or JRE installed on the system, is loaded into a third party-provided class or user-defined class by CLASSPATH environment variables or-classpath this JVM command-line argument. The System class loader delegates the extended class loader to a class that uses the Java extension mechanism. The extended class loader delegates the bootstrap class loader (bootstrap class loader) into the core JDK class.

You can develop special class loaders yourself, customizing how the JVM dynamically loads classes. For example, most servlet engines use custom class loaders to dynamically load classes that have changed in the directory specified by Classpath.

What must be paid special attention to (and surprisingly) is that the order in which class loaders load classes is the order in which classes appear in Classpath. The class loader starts with the first entry in Classpath, examines each set of directories and compressed files sequentially, and tries to find the class files to be loaded. When the class loader first finds a class with the specified name, it loads the class, and all remaining items in the classpath are ignored.

It looks simple, doesn't it?

   Ii. issues that may arise

Whether they are willing to admit it or not, beginners and experienced Java developers alike have been deceived at times, often in the worst cases, by lengthy, complex classpath. The number of Third-party classes and user-defined classes that the application relies on is growing, and classpath is gradually becoming a place where all the possible directories and file names are stacked. At this point, it is no longer obvious what class loader first loads. This problem is especially true if the classpath contains duplicate class portals. As mentioned earlier, the class loader always loads the first class with the proper name it finds in the classpath, and in effect it "hides" other classes with the appropriate name but lower priority in the classpath.

If you are not careful, you can easily fall into this classpath trap. When you end a long day of work, and finally you add a directory to the CLASSPATH for your application to use the best and most up-to-date classes, you forget: Another version of the class is stored in the CLASSPATH's other higher-priority directory!

   三、一个 Simple Classpath Tools

The priority problem is the inherent problem of the flat Path declaration method, but it is not the only Java classpath problem. To solve this problem, you just have to stand on the shoulders of the legendary software giant: the UNIX operating system has a which command that specifies a name in the command parameter, and which displays the pathname of the file when the name executes as a command. In fact, the which command analyzes the path variable and then finds out where the command first appeared. This should also be a good tool for Java classpath Management. Inspired by it, I set out to design a Java tool Jwhich. This tool requires the name of a Java class to be specified, and then according to Classpath's guidance, find the absolute path to the location of the class loader that is about to be loaded.

The following is an example of a jwhich usage. It shows that when the Java class loader loads the Com.clarkware.ejb.ShoppingCartBean class, the first occurrence of the class is the absolute pathname of the position, and the lookup results show that the class is in a directory:

> Java Jwhich com.clarkware.ejb.ShoppingCartBean

Class ' Com.clarkware.ejb.ShoppingCartBean ' found in
'/home/mclark/classes/com/clarkware/ejb/shoppingcartbean.class '

The following is an example of the use of the second Jwhich. It shows that when the Java class loader loads the Javax.servlet.http.HttpServlet class, the first occurrence of the class is the absolute pathname of the position, and the lookup results show that the class is in an archive file:

> Java Jwhich javax.servlet.http.HttpServlet

Class ' Javax.servlet.http.HttpServlet ' found in
' File:/home/mclark/lib/servlet.jar!/javax/servlet/http/httpservlet.class '

  iv. working process of Jwhich

To accurately determine which class in the classpath is loaded first, you must go deep into the class loader thinking method. In fact, it's not as complicated as it sounds-you just have to ask the class loader directly!

1:public class Jwhich {
2:
3:/**
4: * According to the current classpath settings,
5: * Displays the class file containing the specified class
6: * Absolute path of position
7: *
8: * @param className < class name >
9: */
10:public static void which (String className) {
11:
12:if (!classname.startswith ("/")) {
13:classname = "/" + className;
14:}
15:classname = Classname.replace ('. ', '/');
16:classname = ClassName + ". Class";
17:
18:java.net.url Classurl =
19:new Jwhich (). GetClass (). getresource (ClassName);
20:
21:if (Classurl!= null) {
22:system.out.println ("Class" + ClassName +
"' Found in '" + classurl.getfile () + "'");
MORE:} else {
25:system.out.println ("Class" + ClassName +
Num: "' not found in '" +
27:system.getproperty ("Java.class.path") + "'");
28:}
29:}
30:
31:public static void Main (String args[]) {
32:if (Args.length > 0) {
33:jwhich.which (Args[0]);
MORE:} else {
35:system.err.println ("Usage:java Jwhich");
36:}
37:}
38:}

First, you have to adjust the name of the class A little so that the class loader can accept (12-16 lines). Adding a "/" in front of the class's name requires the class loader to match the class name in Classpath verbatim, rather than trying to implicitly add the package name prefix of the calling class. Put all the "." The purpose of converting to "/" is to format the class name into a valid URL resource name, as required by the class loader.

Next, the program queries the class loader for a resource whose name must match the appropriately formatted class name (18-19 lines). Each class object maintains a reference to the ClassLoader object that loaded it, so this is the class loader query that loads the Jwhich class. The Class.getResource () method actually delegates the class loader of the class, returns a URL for reading the class file resource, or, when the specified class name cannot be found in the current classpath, Class.getResource () method returns NULL.

Finally, if the specified class can be found in the current classpath, the program displays the absolute path name (21-24 rows) where the class file containing the class is located. As a debugging aid, if the specified class cannot be found in the current classpath, the program obtains the Java.class.path system properties and displays the current classpath (24-28 rows).

It is easy to imagine how this simple code works in a Java servlet using the servlet engine classpath, or in an EJB component that uses an EJB server classpath. For example, if the Jwhich class is loaded by the custom class loader of the servlet engine, the program will use the Servlet engine's class loader to find the specified class. If the servlet engine's class loader cannot find the class file, it will delegate its parent class loader. Generally, when Jwhich is loaded by a class loader, it can find all classes that are loaded by the current class loader and all its parent class loaders.

   "Closing"

If the need is the mother of all inventions, the tools that help us manage Java Classpath can be said to be a long time late. There are a lot of questions about Classpath in the Java Newsgroups and mailing lists, and now Jwhich provides us with a simple yet powerful tool that helps us to completely play the Java Classpath in any environment.

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.