JAVA教程 JAVA虚拟机电子书

Java是什么 Java培训

Java教程 Inside Class Loaders: Debugging :Andreas Schaefer Java软件学习

Inside Class Loaders: Debuggingby Andreas Schaefer
06/30/2004

Though we discussed the basics of class loading in the previous article in this series, we still need more knowledge before we can delve into the advanced class-loading techniques. This article will show how to solve class-loading problems and to overcome some debugging limitations of the JDK class loaders.

Let me issue a warning here that dealing with class loaders is somewhat risky business, because problems seldom arise during the class-loading process itself. Therefore locating a problem is tricky and time-consuming. That said, custom class loaders can also offer many possibilities regular Java classes cannot achieve, and therefore are essential to advanced applications like servers, code-enhancing tools and dynamic modules. In the end, it is up to the architect to decide if the features outweigh the risks and to make sure that debugging and extended tests are provided.

Tricks of the Trade to Investigate Class-Loading Problems

The biggest challenge in dealing with class-loading problems is that problems rarely manifest themselves during the class-loading process but rather during the usage of a class later on. In addition, the messages provided by the JDK are, to say the least, inadequate, and the toString() methods of the JDK class loaders are not overridden to provide more data.

ClassNotFoundException

Let´s consider several different class-loading error scenarios. First, we want to figure out what to do when a class could not be found and the application throws a ClassNotFoundException that looks like this:

java.lang.ClassNotFoundException: Class: com/madplanet/article/classloader/ part2/NotToBeFoundClass could not be found at com.madplanet.article.classloader. part2.MyClassLoader.findClass (MyClassLoader.java:41) at com.madplanet.article. classloader.part2.MyClassLoader. loadClass(MyClassLoader.java:56) at java.lang.ClassLoader. loadClass(ClassLoader.java:235) at com.madplanet.test.classloader. part2.MainTest.testClassNotFound( MainTest.java:48)

Here are some steps to resolve the issue:

  1. Look for the line where your class loader´s loadClass() call is involved (in our example, the last line).
  2. Figure out what class loader is used there.
  3. Figure out the parent class loaders recursively until you find the bootstrap class loader.
  4. Figure out why the class cannot be found by any of these class loaders.

This problem is caused when a class loader is asked to load a particular class and it cannot be found. Here are few causes: