Java Reflection-Simple application

Source: Internet
Author: User

In order to better maintain and expand the program, in the object-oriented thinking world, the first is interface-oriented programming, and then we should do what and how to separate.

Below I will use an example of a party to demonstrate that the final effect is: Factory + reflection + configuration file implementation of the flexible application. Will specify how this process came, understand this, the reflection and configuration files will be more deeply combined.

To achieve the function is: the party has a singing, dance, sketch of the program, the specific performance of each program only need one can, each performance interface has two implementation classes (performers), through the client call different implementation classes to implement different programs. The performer is "what to do", then "how to Do" is the program, first of all to look at the class diagram structure:

The following code, the first is the interface, that is, various performances:

<span style= "FONT-SIZE:14PX;" >/** Dance Interface */</span><pre name= "code" class= "Java" >public interface dancer {
public void Dance ();} /** Sketch Interface */public interface performer {public void performance (); /** Singing interface */public interface Singer {public void sing ();

Then there are the various implementation classes, namely performers:

Dancer interface Implementation class: public class Yangliping implements dancer {    @Override public   Void Dance () {      System.out.println ("Yang Liping Dance: Peacock Dance");   }  } Public class Xiaohudui implements dancer {    @Override public   Void Dance () {      System.out.println ("Small Tigers Dance: Break Dance") ;   } }performer interface Implementation class: public class Gonghanlin implements performer {    @Override public   Void Performance () {      System.out.println ("Gong Hanlin Show: Kung Fu Order");   }public class Zhaobenshan implements performer {    @Override public   Void Performance () {      System.out.println ("Zhao Benshan performance: Selling");   } }singer interface Implementation class: public class Zhouhuajian implements Singer {    @Override public   void Sing () {      System.out.println ("Emil Chau Singing: Swords as Dream");   } }public class Wangfei implements Singer {    @Override public   void Sing () {      System.out.println ("Faye Wong sings: I Will") ;   } }


Client Invocation Method:

<span style= "FONT-SIZE:14PX;" > public static void Main (string[] args) {           //define the party process      //performance: Song, dance, show      //1th method: Use polymorphism           alone SYSTEM.OUT.PRINTLN ("Party starts =======>>");           Singer Singer = new Zhouhuajian ();      Singer.sing ();           Performer performer = new Zhaobenshan ();      Performer.performance ();           Dancer dancer = new yangliping ();      Dancer.dance ();           System.out.println ("<<======== Party End");   } </span>

The code is simple, but the problem is that, as a program organizer, in reality, it is basically not supposed to deal directly with performers, but with their companies or agents, assuming that all performers now belong to an entertainment company, Then I just need to get the performers I want from this entertainment company, then the UML diagram will be the following structure (factory represents this entertainment company):


Facotry Code:

Public ClassFactory {     //provide Ready singer method public   static Singer Getsinger () {      return new Zhouhuajian ();   }     Provide ready dance method public   static dancer Getdancer () {      return new yangliping ();   }     Provide preparation method public   static Performergetperformer () {      return new Gonghanlin ();}   }

Then the client code becomes this:

Public Staticvoidmain (string[] args) {      //define Party Process      //performance: Song, sketch, Dance      //1th method: Use the factory to get the various           types of performances SYSTEM.OUT.PRINTLN ("Party starts =======>>");           Singersinger = Factory.getsinger ();      Singer.sing ();           Performerperformer = Factory.getperformer ();      Performer.performance ();           Dancerdancer = Factory.getdancer ();      Dancer.dance ();           System.out.println ("<<======== Party End");}


As you can see, in the factory code we find that each implementation class is written dead, that is, the entertainment company forces certain performers to participate, but in fact many times some performers may not be able to participate, while other idle performers can participate, So should I be able to get a better one when I need a performer? This time you need to use the configuration file + reflection. The factory code changes as follows:

<span style= "FONT-SIZE:14PX;" >public class Factory {/** provides the Prepare singer method */public static Singer Getsinger () {//Read config file and get key corresponding value STR      Ingclassname = resourcebundle.getbundle ("Party"). GetString ("Singer");           Singersinger = null;      try {//The full class name read in the configuration file gets the instance singer= (singer) Class.forName (className) of the class through reflection. Newinstance (); }catch (Instantiationexception | illegalaccessexception |      ClassNotFoundException e) {e.printstacktrace ();        } return singer; }/** provides the Prepare dance method */public static dancer Getdancer () {stringclassname = Resourcebundle.getbundle ("Party"). GetS      Tring ("Dancer");           Dancerdancer = null;      try {dancer= (dancer) Class.forName (className). newinstance (); }catch (Instantiationexception | illegalaccessexception |      ClassNotFoundException e) {e.printstacktrace ();   } return dancer; }/** provides preparation for performing methods */public static performergetperformer (){stringclassname = resourcebundle.getbundle ("Party"). GetString ("performer");           Performerperformer = null;      try {performer= (performer) Class.forName (ClassName). newinstance (); }catch (Instantiationexception | illegalaccessexception |      ClassNotFoundException e) {e.printstacktrace ();   } return performer; }}</span>

Code in the configuration file party.properties:

Singer = Com.lc.reflect.demo3.person.WangFeiPerformer = Com.lc.reflect.demo3.person.ZhaoBenShanDancer = Com.lc.reflect.demo3.person.XiaoHuDui

This allows you to decouple the code. Look closely, the code in the factory 3 methods are basically no different, in addition to variables and objects, found the bad taste of the code. Then refactor it:

Public ClassFactory1 {/** provides the Prepare singer method */public static Singer Getsinger () {Singersinger =         Null      Return (Singer) getObject ("Singer", Singer);                 }/** provides the Prepare dance method */public static dancer Getdancer () {dancerdancer = null;      Return (dancer) GetObject ("Dancer", dancer);                 }/** provides the prepare to perform method */public static performergetperformer () {performerperformer = null;      Return (performer) GetObject ("performer", performer); }/** * method to get target object * @param objname object name * @param obj Object type * @return Object */Publ IC Static Object GetObject (Stringobjname,object obj) {//Gets the target object path in the configuration file Stringclassname = Resourceb         Undle.getbundle ("Party"). GetString (objname);         try {//Gets the target object instance obj= class.forname (className). newinstance (); }catch (Instantiationexception | illegalaccessexception | ClasSnotfoundexception e) {e.printstacktrace ();      } return obj; }}

that's a lot more concise.

Learning a piece of knowledge not only to learn how the API is used, but also to combine with life, make a simple and effective demo, at the same time in the process of doing the demo, if found to write the code there is worth refactoring place, must not stop thinking footsteps, Just do it! Although the concrete realization of the principle and process of reflection is not clear, but first will be used to continue to study the power. Continue to work in ~ ~


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Reflection-Simple application

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.