Dynamic load class of java-reflection

Source: Internet
Author: User

In Java, load classes are divided into dynamic loading and static loading, where the load class at compile time is called a static load class, and the load class at runtime is called a dynamic load class.

One of the ways to produce a class object is Class.forName (the "Full name of the class"), which not only represents the class type, but also represents the dynamic load class.

1  PackageCom.example.demo;2 3  Public classDemo {4      Public Static voidMain (string[] args) {5         if(Args[0].equals ("word")) {6Word word =NewWord ();7 Word.start ();8         }9         if(Args.equals ("Excel")) {TenExcel Excel =NewExcel (); One Excel.start (); A         } -     } -}

For example, if we do not create word classes and Excel classes, we will find that this code cannot be compiled, because the new method creates the object by statically loading the class, and at compile time all the classes that may be used are loaded, regardless of whether or not it is used later. There is a drawback to this approach: we have to load all the possible classes, and once we find that a class is not loaded, the other classes cannot be used.

Dynamic loading is the class that needs to be used, which class we load, and we don't have to load all the classes in.

1         Try {2             //dynamically loading classes, loading at run time, compiling does not report any errors3Class C1 = Class.forName (args[0]);4             //create objects of classes by class type--the classes I want to load must all conform to a standard, which means implementing a unified interface5Officeable officeable =(officeable) c1.newinstance ();6}Catch(ClassNotFoundException e) {7             //TODO auto-generated Catch block8 e.printstacktrace ();9}

Dynamic load class of java-reflection

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.