Java reflection-simple application

Source: Internet
Author: User

Java reflection-simple application

For better program maintenance and expansion, in the world of Object-oriented Thinking, interface-oriented programming is the first, and then we should separate what we do from how we do it.

The following is an example of a gala. The final result is: factory + reflection + configuration file to implement flexible application of the program. It will explain in detail how this process came about. If you understand this, you will be more profound in the combination of reflection and configuration files.

The function to be implemented is: there is a program ticket for singing, dancing, and sketch at the gala. The Performer of each program only needs one. Each performance interface has two implementation classes (performers ), the client calls different implementation classes to implement different program orders. The performer is "what to do", and "how to do" is a program list. First, let's look at the class chart structure:

 

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

 

/** Dancing interface */
public interface Dancer {
Public void dance ();}/** sketch interface */public interface timer mer {public void performance ();} /** singing interface */public interface Singer {public void sing ();}

 

 

Then there are various implementation classes, that is, 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 (dancing by the Tigers: dancing by the Tigers) ;}} extends mer interface implementation class: public class GongHanLin implements extends mer {@ Override public void performance () {System. out. println (Hanlin performance: Kung Fu) ;}} public class ZhaoBenShan implements extends mer {@ 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 (Zhou huajian SINGING: sword as a dream);} public class WangFei implements Singer {@ Override public void sing () {System. out. println (Faye Wong SINGING: I want );}}


 

Client call method:

 

Public static void main (String [] args) {// defines the Party process // performances: songs, dances, performances // 1st Methods: simply use the polymorphism System. out. println (party start ========>>); Singer singer = new ZhouHuaJian (); singer. sing (); timer mer = new ZhaoBenShan (); timer mer. performance (); Dancer dancer = new YangLiPing (); dancer. dance (); System. out. println (<======= end of the Party );}

 

The code is quite simple, but I found a problem. As a Program Organizer, in reality, it is basically not necessary to deal with performers directly, but to communicate with the company or agent where the program is located, assuming that all the performers belong to the same entertainment company, I only need to get the performers I want from this entertainment company, the UML diagram will be changed to the following structure (Factory represents the entertainment company ):

 

Facotry code:

 

Public classFactory {// provides the Singer preparation method public static Singer getSinger () {return new ZhouHuaJian () ;}// provides the dance preparation method public static Dancer getDancer () {return new YangLiPing () ;}// provides the preparation method for the performance. public static synchronized mergetperformer () {return new GongHanLin ();}}

 

 

Then the client code becomes like this:

 

Public staticvoidmain (String [] args) {// defines the gala process // performances: songs, sketches, and dances // 1st Methods: Use the factory to obtain various types of performances System. out. println (party start ======>>); Singersinger = Factory. getSinger (); singer. sing (); mercurmer = Factory. getcyclmer (); cyclmer. performance (); Dancerdancer = Factory. getDancer (); dancer. dance (); System. out. println (<======= end of the Party );}


 

As you can see, in the Factory code, we find that each implementation class is dead. That is to say, entertainment companies force certain performers to participate, but in fact some performers may not be able to participate in many times, other idle performers can participate. Should I dynamically obtain free performers when I need them? At this time, you need to use the configuration file + reflection. The Factory code is changed as follows:

 

Public class Factory {/** provides the preparation method */public static Singer getSinger () {// reads the configuration file and obtains the value StringclassName = ResourceBundle corresponding to the key. getBundle (party ). getString (Singer); Singersinger = null; try {// obtain the instance singer = (Singer) Class of this Class by reflecting the complete Class name read in the configuration file. forName (className ). newInstance ();} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {e. printStackTrace ();} return singer;}/** provides the dance Preparation Method */public static Dancer getDancer () {StringclassName = ResourceBundle. getBundle (party ). getString (Dancer); Dancerdancer = null; try {dancer = (Dancer) Class. forName (className ). newInstance ();} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {e. printStackTrace ();} return dancer;}/** provides the preparation method */public static variable mergetperformer () {StringclassName = ResourceBundle. getBundle (party ). getString (timer mer); extends Mermer mer = null; try {timer mer = (timer mer) Class. forName (className ). newInstance ();} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {e. printStackTrace ();} return timer mer ;}}

 

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 decouples the code. If you look at it carefully, the three methods of code in the Factory are basically no different. Except for the differences between variables and objects, the bad taste of the Code is found. Let's refactor it:

 

Public classFactory1 {/** provides the method for preparing singers */public static Singer getSinger () {Singersinger = null; return (Singer) getObject (Singer, singer );} /** provides the dance Preparation Method */public static Dancer getDancer () {Dancerdancer = null; return (Dancer) getObject (Dancer, dancer );} /** provides the preparation method */public static variable mergetperformer () {Variable merperformer = null; return (sort mer) getObject (sort mer, sort mer );} /*** method for obtaining the target Object * @ param objName Object name * @ param obj Object type * @ return Object */public static Object getObject (StringobjName, Object obj) {// obtain the target object path in the configuration file StringclassName = ResourceBundle. getBundle (party ). getString (objName); try {// get the target object instance obj = Class. forName (className ). newInstance ();} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {e. printStackTrace ();} return obj ;}}

This is much simpler.

 

To learn a piece of knowledge, we should not only learn how to use APIs, but also combine them with our daily lives to make simple and effective demos. At the same time, during the Demo process, if you find that the written code is worth restructuring, do not stop thinking, Just do it! Although we are not quite clear about the specific implementation principles and processes of reflection, we will first use it to provide the motivation for further research. Continue to work ~~


 

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.