An example of static loading and dynamic loading of Java reflection

Source: Internet
Author: User

Static loading:

Package COM.IMOOC. Load class, public class Office_static {public static void main (string[] args) {//new creates an object, is a static load class, At compile time you need to load all the possible classes if ("word". Equals (Args[0])) {Word w = new Word (); W.start ();} if ("Excel". Equals (Args[0])) {Excel e = new Excel (); E.start ();}}}
This program must be compiled with Word and Excel two classes exist before the line, even if you do not use Excel to load


Dynamic loading:

1, Interface officeable:

Package COM.IMOOC. Load class; public interface officeable {public void Start ();}
2, Word implementation interface:

Package COM.IMOOC. Load class, public class Word implements Officeable{public void Start () {System.out.println ("Word start");}}
3, Excel Implementation interface:


Package COM.IMOOC. Load class, public class Excel implements Officeable{public void Start () {System.out.println ("Excel start");}}

4. Main method

Package COM.IMOOC. Load class, public class Officebetter {/** * @param args */public static void main (string[] args) {try {//Dynamically load class, Load Class C = Class.forName (Args[0]) at run time;//Enter COM.IMOOC in the Run configuration. Load class. excel//creates the class object through the class type ( Convert first to Word and Excel Common interface officeable) officeable OA = (officeable) c.newinstance (); Oa.start ();//not recommended for the following two kinds, Because you are not sure whether to load Word or Excel, go//word Word = (word) c.newinstance ();//word.start ();//excel Excel = (Excel) c.newinstance ();// Excel.start ();} catch (Exception e) {e.printstacktrace ();}}}



An example of static loading and dynamic loading of Java reflection

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.