Static Loading and dynamic loading of Java classes, as well as noclassdeffounderror and classnotfoundexception

Source: Internet
Author: User

We all know that Java can use the new operator to initialize a class, or use the class. forname method to get a class type instance, and then initialize through the newinstance of this class type instance. we call the former Java static loading and the latter dynamic loading. the latter is often used in many frameworks, and the class name is specified by using the property file. for example, we are familiar with loading drivers of different databases when writing JDBC code.

If the class to be initialized cannot be found in the runtime environment during static loading, noclassdeffounderror is thrown, which is an error in the Java exception system.

During dynamic state Loading, if the class to be initialized cannot be found in the runtime environment, classnotfoundexception is thrown, which is a checked exception in the Java exception system, catch is required when writing code.

The following example demonstrates that referencedcls is the class to be initialized. It is in a separate jar and is loaded by staticreferencingcls and dynamicreferencingcls in both static and dynamic ways.

Make prjt1 a jar package, t1.jar. Make prjt2 a jar package, and put t2.jar. In the D:/Temp folder.

The Java code is as follows:

package com.test1;public class ReferencedCls {private String str = "test value";public String getStr() {return str;}public void setStr(String str) {this.str = str;}public ReferencedCls() {System.out.println("Constructor: ReferencedCls");}}package com.test2;import com.test1.ReferencedCls;public class StaticReferencingCls {public static void main(String[] args) {System.out.println("Started testing static loading...............");ReferencedCls cls = new ReferencedCls();System.out.println(cls.getStr());}}package com.test2;import com.test1.ReferencedCls;public class DynamicReferencingCls {public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {System.out.println("Started testing dynamic loading...............");Class cls = Class.forName("com.test1.ReferencedCls");ReferencedCls obj = (ReferencedCls)cls.newInstance();System.out.println(obj.getStr());}}

Run in different ways:
1. All required classes are running normally in the running environment.

D:\>java -cp d:/temp/t1.jar;d:/temp/t2.jar com.test2.StaticReferencingClsStarted testing static loading...............Constructor: ReferencedClstest valueD:\>java -cp d:/temp/t1.jar;d:/temp/t2.jar com.test2.DynamicReferencingClsStarted testing dynamic loading...............Constructor: ReferencedClstest value

2. Load in static mode. If the runtime environment lacks the required classes, noclassdeffounderror is thrown.

D:\>java -cp d:/temp/t2.jar com.test2.StaticReferencingClsStarted testing static loading...............Exception in thread "main" java.lang.NoClassDefFoundError: com/test1/ReferencedCls        at com.test2.StaticReferencingCls.main(StaticReferencingCls.java:9)Caused by: java.lang.ClassNotFoundException: com.test1.ReferencedCls        at java.net.URLClassLoader$1.run(Unknown Source)        at java.security.AccessController.doPrivileged(Native Method)        at java.net.URLClassLoader.findClass(Unknown Source)        at java.lang.ClassLoader.loadClass(Unknown Source)        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)        at java.lang.ClassLoader.loadClass(Unknown Source)        at java.lang.ClassLoader.loadClassInternal(Unknown Source)        ... 1 more

3. dynamically load the required classes in the runtime environment and throw classnotfoundexception. At the same time, you must catch or declare this exception when writing code.

D:\>java -cp d:/temp/t2.jar com.test2.DynamicReferencingClsStarted testing dynamic loading...............Exception in thread "main" java.lang.ClassNotFoundException: com.test1.ReferencedCls        at java.net.URLClassLoader$1.run(Unknown Source)        at java.security.AccessController.doPrivileged(Native Method)        at java.net.URLClassLoader.findClass(Unknown Source)        at java.lang.ClassLoader.loadClass(Unknown Source)        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)        at java.lang.ClassLoader.loadClass(Unknown Source)        at java.lang.ClassLoader.loadClassInternal(Unknown Source)        at java.lang.Class.forName0(Native Method)        at java.lang.Class.forName(Unknown Source)        at com.test2.DynamicReferencingCls.main(DynamicReferencingCls.java:11)

4. The JVM itself uses static loading. For example, if a class with the main method is run using Java commands, this class is missing in the runtime environment.

D:\>java com.test2.XXXClsException in thread "main" java.lang.NoClassDefFoundError: com/test2/XXXClsCaused by: java.lang.ClassNotFoundException: com.test2.XXXCls        at java.net.URLClassLoader$1.run(Unknown Source)        at java.security.AccessController.doPrivileged(Native Method)        at java.net.URLClassLoader.findClass(Unknown Source)        at java.lang.ClassLoader.loadClass(Unknown Source)        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)        at java.lang.ClassLoader.loadClass(Unknown Source)        at java.lang.ClassLoader.loadClassInternal(Unknown Source)Could not find the main class: com.test2.XXXCls.  Program will exit.
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.