Java Reflection--dynamic loading

Source: Internet
Author: User

Class.forName ("Full name of the class")

1) not only represents the class type of the class, but also represents the dynamic load class

2) Please distinguish compile, run

3) Compile time load class is static load class, run time load class is dynamic load class

such as the following:

For example, a class has the following method, when the condition satisfies word, call word w=new word ();

When Excel is satisfied, call Excel e=new Excel ();

This method of using new to create an object belongs to the static load class, compile time will need to load all possible classes, once Word or Excel does not exist, compile the time will be error, pass.

If I want to use which class, load which class, only use the time, only to load, then can solve this problem.

The problem can be furnished by dynamically loading the class.

The specific implementation is as follows:

 Package Com.reflect;  Public class Officebetter {    publicstaticvoidthrows  Exception {            Class C1=class.forname ("Com.reflect.Word");                        officeable OA=(officeable) c1.newinstance (); by instantiating a total object through Newinstance (), in order for the different classes to be able to convert, you need to define a total interface for these classes            Oa.start ();}        }

Instantiate this class of objects through the Newinstance method, but if the word class needs to be converted to word, if it is an Excel class, it needs to be converted to an Excel class,

For convenience, it is possible to define altogether a common interface for these several classes, officeable. The required class implements its interface.

 Package Com.reflect;  Public Interface officeable {        publicvoid  start ();}

Word implements an interface

 Package Com.reflect;  Public class Implements officeable {    @Override    publicvoid  start () {        System.out.println ("word...is created");}    }

What kind of class is needed, just in this way.

Java Reflection--dynamic loading

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.