Java Interface, Reflection

Source: Internet
Author: User

Look at the code first,

  

Package Reflect;//class Wordpublic Class Word implements officeable{public static void Main (string[] args) {}public void St Art () {System.out.println ("Word...start ...");} Public Word () {}}package Reflect;//class excelpublic Class Excel implements officeable{public static void Main (string[] Ar GS) {}public void start () {}public Excel () {}}package reflect;//officeable interface, implemented by classes such as Word and Excel interface officeable {public void Start ();} Test method Package Reflect;import Org.junit.test;public class Test01 {@Testpublic void Testor () throws ClassNotFoundException, instantiationexception, illegalaccessexception{//dynamic load class, loading//class a = Class.forName at run time (" Reflect. Word "); Class a = Class.forName ("reflect. Excel "); System.out.println ("A:" +a);//a:class reflect. EXCEL//creates the class object through the class type officeable OA = (officeable) a.newinstance (); Oa.start ();}}

  

Java interface benefits are obvious, such as class Word and class Excel are implemented Officeable interface, so for example to call the Word.start () method, when instantiating the word class, not necessarily cast to word, Instead, you can cast directly to the officeable type, and then call the start () method. The only job that needs to be done is to pass in the class to be used in the Class.forName (), and in this case the parameter passed in is "package." ClassName ", i.e." reflect. Word ", and if you need to instantiate Excel, you can just change the classname to Excel when you load the class.

Java Interface, 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.