Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deeply discuss and understand the CLASSPATH of Java

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces you how to deeply discuss and understand the CLASSPATH of Java. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

On the face of it, Java's classpath (classpath) is simple, but it has always been a source of problems and confusion. This article introduces the basics of classpath, the problems that may arise, and provides a simple classpath management tool.

Developers occasionally run into trouble when dealing with Java classpath (classpath). This is because it is sometimes not obvious which class the class loader actually loads, especially when the application's classpath contains a large number of classes and directories. This article will provide a tool that displays the absolute pathname of the loaded class file.

I. Foundation of Classpath

The Java virtual machine (JVM) loads the classes used by the application with the help of the class loader, and which classes are loaded according to the needs at that time. The CLASSPATH environment variable tells the class loader where to find third-party supplied and user-defined classes. 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 in the classpath can be: the directory of the file (containing classes that are not in the package), the root directory of the package (containing the packaged classes), and the archive file containing the class (such as .zip file or .jar file). On Unix family systems, items in the classpath are separated by colons, and on MS Windows systems, they are separated by semicolons.

Class loaders are organized in a delegate hierarchy, and each class loader has a parent class loader. When a class loader is asked to load a class, it delegates the request to its parent class loader before trying to find the class itself. The system class loader, that is, the default class loader provided by JDK or JRE installed on the system, loads third-party classes or user-defined classes through the CLASSPATH environment variable or the JVM command line parameter-classpath. The system class loader delegates the extension class loader to load classes that use the Java Extension mechanism. The extension class loader delegates the bootstrap class loader (bootstrap class loader) to load the core JDK class.

You can develop your own special class loader to customize how JVM loads classes dynamically. For example, most Servlet engines use custom class loaders to dynamically load classes that change within the directory specified by classpath.

It is important to note (and surprisingly) that the order in which the class loader loads the class is the order in which the class appears in classpath. Starting with the first item of classpath, the class loader examines each set directory and zip file in turn to try to find the class file 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.

Looks simple, doesn't it?

2. Problems that may arise

Whether they are willing to admit it or not, both beginners and experienced Java developers have been deceived by lengthy, complex classpath at some point (usually in the worst cases). The number of third-party and user-defined classes that applications rely on is growing, and classpath is becoming a place to pile up all possible directory and file names. At this point, it is no longer obvious which class the class loader loads first. This problem is particularly acute if the classpath contains duplicate class entries. As mentioned earlier, the class loader always loads the first class with the right name it finds in classpath, and in practice, it "hides" other classes with appropriate names but lower priority in classpath.

If you are not careful, you can easily fall into this classpath trap. After a long day's work, you finally add a directory to classpath to make your application use the best and latest classes, but at the same time, you forget: another version of this class is stored in another higher priority directory in classpath!

3. A simple classpath tool

Priority issues are inherent in the flat path declaration approach, but they are not unique to Java's classpath. To solve this problem, you only need to stand on the shoulder of the legendary software giant: the Unix operating system has a which command, specify a name in the command parameters, and which will display that name as the path name of the execution file when the command is executed. In fact, the which command is to analyze the PATH variable and find 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 you to specify the name of a Java class, and then follow classpath's guidance to find out the absolute path to the location of the class that the class loader is about to load.

The following is an example of using JWhich. It shows the absolute pathname of the location where the Java class appears for the first time when the com.clarkware.ejb.ShoppingCartBean class is loaded by the com.clarkware.ejb.ShoppingCartBean class loader, and the search 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 a second example of using JWhich. It shows the absolute pathname of the location where the Java class first appears when the javax.servlet.http.HttpServlet class is loaded by the javax.servlet.http.HttpServlet class loader, and the search results show that the class is in an archive file:

> java JWhich javax.servlet.http.HttpServlet

Class' javax.servlet.http.HttpServlet' found in 'fileWrap bank HttpServlet.class'

IV. The working process of JWhich

To determine exactly which class in the classpath is loaded first, you must delve into the thinking of the class loader. In fact, the implementation is not as complicated as it sounds-all you have to do is ask the class loader directly!

1: public class JWhich {

2:

3: / *

4: * according to the current classpath settings

5: * shows where the class file containing the specified class is located

6: * absolute path to the location

7: *

8: * @ param className

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:

Public static void main (String args) {

32: if (args.length > 0) {

JWhich.which (args [0])

34:} else {

35: System.err.println ("Usage: java JWhich")

36:}

37:}

38:}

First, you must adjust the name of the class slightly so that the class loader can accept it (lines 12-16). Adding a "/" to the name of the class means that the class loader is required to match the class name exactly in classpath, rather than trying to implicitly prefix the package name of the calling class. Put all "." The purpose of the conversion to "/" is to format the class name into a legal URL resource name as required by the class loader.

Next, the program queries the class loader for a resource whose name must match the properly formatted class name (lines 18-19). Each Class object maintains a reference to the ClassLoader object on which it is loaded, so here is a query from the classloader that loads the JWhich class. The Class.getResource () method actually delegates the class loader that loads the class, returning a URL; for reading the class file resources, or the Class.getResource () method returns null if the specified class name cannot be found in the current classpath.

Finally, if the specified class can be found in the current classpath, the program displays the absolute pathname of the location of the class file containing the class (lines 21-24). As a debugging aid, if the specified class cannot be found in the current classpath, the program gets the java.class.path system property and displays the current classpath (lines 24-28).

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

If need is the mother of all inventions, the tool that helps us manage the Java classpath can be said to be long late. Java newsgroups and mailing lists are full of questions about classpath, and now JWhich provides us with a simple but powerful tool to help us thoroughly play with the Java classpath in any environment.

On how to in-depth discussion, understanding of Java CLASSPATH to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report