Using the Class.forName () load class under Java programming

Source: Internet
Author: User

In some applications, it is not possible to know in advance what class the consumer will load, but must let the user specify the class name to load the class, and you can implement the dynamic load class using the class's Static forname () method. The following example allows you to specify the class name to obtain information about the class.

Package Cn.sunzn.demo;public class Classdemo {public    static void Main (string[] args) {        try {            Class C = class. Forname (Args[0]);            System.out.println ("Class name:" + c.getname ());            SYSTEM.OUT.PRINTLN ("is interface:" + c.isinterface ());            System.out.println ("is the base type:" + c.isprimitive ());            System.out.println ("is the array:" + C.isarray ());            System.out.println ("Parent class:" + C.getsuperclass (). GetName ());        } catch (ArrayIndexOutOfBoundsException e) {            System.out.println ("No class name specified");        } catch (ClassNotFoundException e) {            System.out.println ("Cannot find the specified class");}}}    

When the specified class is given the Forname () method, a ClassNotFoundException exception is thrown if the specified class is not found. The static forname () method of class has two versions, the code above specifies only the version of the class name, and the other version allows you to specify the class name, whether to run static chunks at load time, and to specify the ClassLoader:

Static Class forname (String name, Boolean initialize, ClassLoader loader)

By default, when a class is loaded, it is run if a static chunk is defined in the class. You can use the second version of Forname () to set initialize to False so that static chunks are not run immediately when the class is loaded and static chunks are run when the class is used to build the object. To prove this, you can design a test class first.



Package Cn.sunzn.demo;public class TestClass { static { System.out.println ("[Run static Block]"); } }

Only static chunks are defined in the test class TestClass to display a piece of information to see when a static chunk is running. You can design the example ForNameDemo1 using the first version of the Forname () method.

Test class: ForNameDemo1

Package Cn.sunzn.demo;public class ForNameDemo1 {public static void Main (string[] args) { try { System.out.println ("Loading TestClass"); Class C = class.forname ("Cn.sunzn.demo.TestClass"); System.out.println ("Use TestClass Declaration reference name"); TestClass test = null; System.out.println ("Use TestClass to build Objects"); Test = new TestClass (); } catch (ArrayIndexOutOfBoundsException e) { System.out.println ("No class name specified"); } catch (ClassNotFoundException E { System.out.println ("Cannot find the specified class")}}}

The results of the operation are as follows:

Load TestClass [run static block] Use the TestClass declaration reference name to create an object using TestClass

As you can see from the running results, the first version of the Forname () method runs the static block of code immediately after the class is loaded. Let's look at how the second version of the Forname () method is used in example ForNameDemo2.

Test class: ForNameDemo2

Package Cn.sunzn.demo;public class ForNameDemo2 {public static void Main (string[] args) { try { System.out.println ("Loading TestClass"); Class C = class.forname ("Cn.sunzn.demo.TestClass", False, Thread.CurrentThread (). Getcontextclassloader ()); System.out.println ("Use TestClass Declaration reference name"); TestClass test = null; System.out.println ("Use TestClass to build Objects"); Test = new TestClass (); } catch (ArrayIndexOutOfBoundsException e) { System.out.println ("No class name specified"); } catch (ClassNotFoundException E { System.out.println ("Cannot find the specified class")}}}

The results of the operation are as follows:

Loading TestClass using the TestClass declaration reference name to create an object using TestClass [run static chunks]

Since the second version of the Forname () method is used, the set initialize is false, so static chunks are not run immediately when the class is loaded, and static chunks are run when the class is used to build the object, and the second version of the forname () method requires a classloader. The class loader for the main thread is used in the example.

Using the Class.forName () load class under Java programming

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.