Java tip 105: Use jwhich to master the class path

Source: Internet
Author: User

Java tip 105: Use jwhich to master the class path

Determine which classes in the class path will be loaded

Prepared by Mike Clark

Summary

Although Java class paths seem to be a simple concept, they are often the source of confusion and trouble. This article will show you a simple tool that can clearly determine what Java classes are loaded by the Class Loader from your class path. (1,000 words)

Developers often encounter some embarrassment when processing Java class paths: they do not always know what classes the classloader will load, especially in applications.ProgramThis is especially true when the class path is flooded with a large number of paths and files. In this article, I will introduce a tool that displays the absolute path of the loaded class file.

Class path

Java Virtual Machine (JVM) uses a class loader to load the required classes according to the needs of the application. The classpath environment variable tells the Class Loader where to find a third-party or user-defined class. You can also use the-classpath JVM command line parameter to specify a class path for each application. This path will overload the class path specified by the classpath environment variable.

Or. Jar files ). Paths in a class path are separated by colons in Unix-type systems and separated by semicolons in MS Windows systems.

The class loader is organized in the form of a delegate tree. Each class loader has a parent class loader. When the system requires a class loader to search for a class, it first delegates the request to its parent class loader before searching for the class. The default Class Loader provided by JDK or JRE in your system is the system class loader. It uses the classpath environment variable or-classpath JVM command line parameter to load third-party and user-defined classes. The system class loader delegates the extension class loader to load classes that use the Java extension mechanism. The extended Class Loader delegates the self-guided Class Loader (delegated until now) to load the JDK core class.

You can develop a specific class loader to guide the JVM on How to dynamically load classes. For example, most servlet engines use a custom Class Loader. When the class in the specified class path changes, it can dynamically re-call these Servlet classes.

Here, it is very important and surprising that the class loader loads classes according to their storage order in the class path. Starting from the first path, the Class Loader accesses each specified directory or compressed file to find the class to be loaded. It loads the first class that matches the name, and the remaining path is ignored.

It sounds simple, right?

Traps in the class path

The novice and veteran of Java developers are often fooled by troublesome class paths, regardless of whether they admit it or not. With the increase of third-party and user-defined classes in the application, the class path becomes congested. Therefore, it is not always obvious which class is first loaded by the class loader, this is particularly prominent when the classless path contains the path dual copy. Remember that the class loader loads the first class with a matched name and hides other classes with the same name and lower priority "effectively.

It seems so simple that we cannot fall into the trap of class path. Let's take a look. After a hard day of keyboard operations, you want to add a directory in the class path so that the application can call the latest version of a class. However, you have not noticed that another version of this class is already in a directory with a higher priority. That's it!

Jwhich: A simple class path tool

The priority issue in the flat path declaration is not exclusive to Java class paths. To solve this problem, you just need to stand on the shoulders of the legendary software giant. The which command of the UNIX operating system accepts a name as a parameter. As long as the name is a command, it displays the path of the relevant executable file. This command first scans the PATH environment variable and determines the first position of the command to be searched. This sounds like a powerful tool for managing Java class paths. Inspired by this idea, I began to write a Java program. This program can display the absolute path of the class file to be loaded based on a Java class name, which is consistent with the path specified in the class path.

The following jwhich example shows the absolute path of the class com. clarkware. EJB. shoppingcartbean. It is the first path encountered when the class loader loads the class and belongs to the directory:

> JAVA jwhich com. clarkware. EJB. shoppingcartbean

Class 'com. clarkware. EJB. shoppingcartbean' found in

'/Home/mclark/classes/COM/clarkware/EJB/shoppingcartbean. class'


The following jwhich example shows the absolute path of the class javax. servlet. http. httpservlet. It is the first path encountered when the class loader loads the class, which is a compressed 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'


How jwhich works

To fully determine which class in the class path will be loaded, you must understand the "idea" of the class loader ". This is not as difficult as it sounds-simply ask it! The following are related to jwhich:Code. For all the code, see resources.


1: Public class jwhich {

2:

3 :/**

4: * prints the absolute pathname of the class file

5: * containing the specified class name, as prescribed

6: * by the current classpath.

7 :*

8: * @ Param classname name of the class.

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 ("\ nclass" + classname +

23: "'found in \ N'" + classurl. GetFile () + "'");

24:} else {

25: system. Out. println ("\ nclass" + classname +

26: "'Not found in \ N'" +

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]);

34:} else {

35: system. Err. println ("Usage: Java jwhich <classname> ");

36 :}

37 :}

38 :}

First, you need to adjust the class name slightly so that the class loader can accept it (12th-16 rows ). Add "/" before the class name instead of the name of the package that loads the class. This instructs the class loader to check the class name in the class path. Changing "." to "/" can change the class name to a valid URL address. The class loader must use this format.

Next, the system queries the resources (rows 18th-19) that match the class name in the given format from the class loader ). Each class object has a reference to the classloader object loaded on it, so the system will query the Class Loader object loaded into the jwhich class. The class. getresource () method is used to delegate the class loader that loads the class to perform operations. It returns the URL address of the class file resource. If the class file resource with the specified class name is not in the current class path, it returns NULL.

Finally, if the class file resource with the specified class name is in the current class path, the system will display its absolute path (21st-24 rows ). As a debugging method, if the class file is not in the current class path, you will get the value of the Java. Class. Path System attribute, that is, display the current class path (lines 24th-28 ).

In java servlet using the servlet engine class path or engerprise JavaBean (EJB) using the EJB server class path, we can easily imagine how the above simple code is loaded. For example, in the servlet engine, if a custom Class Loader loads the jwhich class, the system will use the class loader of the servlet engine to find the class. If the servlet engine Class Loader cannot find a class, it will delegate it to its parent class loader. Generally, when a Class Loader loads jwhich, its class loader or the class to be loaded by a parent class loader can be found.

Conclusion

If the demand is the mother of invention, it is too late to help manage Java class paths. Java-related newsgroups and email lists are full of class Path Problems. We need to reduce the barriers for new developers to enter this field so that we can continue to work at a higher level. Jwhich is a simple and powerful tool that helps you understand Java class paths in any environment.


About the author

Mike Clark is an independent consultant at clarkware consulting and specializes in Java-based structure design and development using J2EE technology. He recently completed the development and release of a B2B XML Exchange Server. Currently, he is a project consultant who wants to build a J2EE performance management product.

Resources

DownloadArticleCode in:

Http://www.javaworld.com/javatips/javatip105/jwhich.zip

The full version of jwhich with the classiclink validator can be obtained at the following URL:

Http://www.clarkware.com/software/jwhich.zip

For the official documents of Sun JDK and how it handles the class paths on different platforms, see the following documents:

Http://java.sun.com/j2se/1.3/docs/tooldocs/findingclasses.html

For more information about how to set a class path on UNIX and Windows platforms, see "set a class path" below ":

Unix:
http://java.sun.com/j2se/1.3/docs/tooldocs/solaris/classpath.html
Windows:
http://java.sun.com/j2se/1.3/docs/tooldocs/win32/classpath.html
View all previous Java tips and submit your own tips:
http://www.javaworld.com/javatips/jw-javatips.index.html
to get more java skills, please subscribe to the free Java tutor newsletter of itworld.com:
http://www.itworld.com/cgi-bin/subcontent12.cgi
author in the Java World GEO FF Friesen presided over the Java beginners Forum comments:
http://www.itworld.com/jump/jw-javatip105/forums.itworld.com/webx? 14 @. ee6b804/1195! Skip = 1125

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.