Wednesday, May 25, 2011

Common Class Loading Issues (java)

  • ClassNotFoundException
    • Thrown when an application tries to explicitly load a class using class name string and class (.class file) is not found in the classpath.
      Eg. Thrown when an application tries to load a class through its string name using:
      • The forName method in Class.
      • The findSystemClass method in ClassLoader.
      • The loadClass method in ClassLoader.

      By throwing a ClassNotFoundException, the class loader informs us that the bytecode required to define the class is not present in the locations where the class loader is looking for it. There may be classes in a system that cannot be seen by a class loader. This is because a class loader only sees classes that are loaded by itself or loaded by class loaders to which it has a reference. In the class loading delegation model, the classes that are visible to a class loader are those that are loaded by itself or loaded by its parent – in other words, a class loader cannot look down.
    • Can be easily checked by enabling verbose:class JVM argument

  • NoClassDefFoundError
    • Thrown if the ClassLoader instance tries to implicitly load in the definition of a class and no definition of the class could be found.
      The searched for class definition existed when the currently executing class was compiled but the definition can no longer be found. Essentially this means that a NoClassDefFoundError is thrown as a result of a unsuccessful implicit class load.
  • ClassCastException
    • Thrown as a result of incompatible types being found in a type comparison. It indicates that the code has attempted to cast an object to a subclass of which it is not an instance. (remember ClassLoader Namespace)
    • Two classes of the same fully qualified name are not equal to each other if they are loaded by different ClassLoaders. They cannot be cast to each other and such operations would result in a ClassCastException
  • UnsatisfiedLinkError
    It occurs during the resolving stage of the linking phase when a program tries to load an absent or misplaced native library.
  • ClassCircularityError
    It is thrown if a class if a class or interface could not be loaded because it would be its own superclass or superinterface.
  • ClassFormatError
    • This exception is thrown during the verification stage of the linking phase of class loading. The binary data can be malformed if the bytecodes have been changed --if the major or minor number has been changed, for instance. This could occur if the bytecodes had been deliberately hacked, for example, or if an error had occurred when transferring the class file over a network.
    • The only way to fix this problem is to obtain a corrected copy of the bytecodes, possibly by recompiling.

No comments:

Post a Comment