Examples of Java reflection and factory pattern implementations

Source: Internet
Author: User

First, the reflection of Java

In the study of reflection when it is not very clear, now read some information to study carefully, temporarily record the moment's notes.

1, the concept of Java reflection:

  It is the Java program runtime that determines which class is loaded, and the compiler does not know which class to load. This characteristic is reflection. the reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the method of the object is called the reflection mechanism of the Java language.

In fact, our local IDE uses this mechanism, and when we type in a class name and then press the. Dot number, it automatically prompts you which classes of property methods you can use.

2, the role of Java reflection:

Decompile:. Class-Java

Access all information for a class:

-Gets the access modifiers, members, methods, construction methods, and superclass information for a class.

-Seizure of constants and method declarations belonging to an interface.

-Create an instance of a class that does not know the name until the program runs.

-Gets and sets the member of an object, even the name of this member is

In fact, the main role of two kinds:

The extension of unknown applications, such as in the program defines a number of interfaces, as long as the implementation of these interfaces of the DLL can be inserted into the program as a plug-in, then how to implement, you can through reflection, the DLL loaded into memory and then reflected in the method of invoking the DLL.

Second, load the configuration file, the compiler can not know the class name, how to use the Dead method call new Classname (); Reflection must be used to create an object get instances and methods.

3. Common methods of obtaining API

 class Demo1 ...        Class  <?> class1 = null  ;        Class  <?> class2 = null  ;        Class  <?> class3 = null  ;  //  This is generally the way to implement a class object created by  Class1 = class. Forname ("reflect.    Demo1 "); //   Use the package name plus the class name to  Class2 = new   Demo1 (). GetClass (); CLASS3  = Demo1. class ; 
 Public Static void throws classnotfoundexception {        Class<?> c = class.forname ("Java.lang.Integer");         = c.getdeclaredmethods ();//Gets all declared methods        in the class for (method   method:methods) {            System.out.println (Method.tostring ());        }    }

Second, Factory mode + Reflection Example

1, introduce the Factory mode:

The factory method pattern is the further abstraction and generalization of the simple factory model, and the factory method pattern is not only determined by a factory class which product should be instantiated, this decision is given to the subclass of the abstract factory.

Composition

1) Abstract Factory role: This is the core of the factory method pattern, which is independent of the application. is the interface that the specific factory role must implement or the parent class that must inherit. In Java it is implemented by an abstract class or interface.

2) Specific factory role: it contains code related to the specific business logic. Called by the application to create an object that corresponds to a specific product.

3) Abstract Product role: It is the parent of a specific product inheritance or an interface implemented. In Java, there are generally abstract classes or interfaces to implement.

4) Specific product roles: the object created by the specific factory role is an instance of this role. Implemented in Java by a specific class.
The factory method pattern uses multiple subclasses that inherit from the abstract factory role to replace the "God Class" in the simple factory pattern. This, as mentioned above, shares the pressure on the object, and this makes the structure flexible--When a new product (ie, the upstart car) is produced, it can be used by the customer as long as it is generated by the contract provided by the abstract product role and the abstract factory role, without having to modify any existing code. We can see that the structure of the factory role is also in line with the closed principle!

2, Example Introduction

Abstract Product Interface

 Package Factory.unit; // defining an abstract product interface  Public Interface Animal {    publicvoid  Eatfood ();}

Implement two specific product roles

 //  Create a new dog class to implement the animal interface, and implement its method  Span style= "COLOR: #0000ff" >public  class  Dog implements   animal{@Override  public  void   Eatfood () {System.out.println (" Dog eats meat ————————————————    ———— "); }    }
// Create a new cat class to implement the animal interface and implement its methods  Public class Implements animal{    @Override    publicvoid  Eatfood () {        //  TODO auto-generated Method Stub        System.out.println ("Cat Eats fish *****************");}    }

Implement Factory class

By the way, insert a singleton mode of explanation: Others ' blog: http://blog.csdn.net/jason0539/article/details/23297037/

ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException;Importjava.util.Properties; Public classFactory {//to create a private static properties object    Private StaticProperties Pro =NewProperties (); //Load configuration file    Static{        Try{pro.load (NewFileInputStream ("file.txt")); } Catch(IOException e) {E.printstacktrace (); }    }    //Singleton mode, which guarantees that the class can only create one object    Private StaticFactory FC =NewFactory (); PrivateFactory () {}//Static can have a direct class name. Call     Public StaticFactory getfactory () {returnFC; }        //This method is a public method that is used to produce an interface object     PublicAnimal GetInterface () {//Defining Interface ObjectsAnimal am =NULL; Try{            //based on the key, gets the value in the file, where the value is the full path of the classString ClassInfo = Pro.getproperty ("Classpath"); //use launch to generate class objectclass<?> C =Class.forName (ClassInfo); //gets the instance of the class objectObject obj =c.newinstance (); //converting an instance object into an interface objectam=(Animal) obj; }Catch(Exception e) {e.printstacktrace (); }        //return Interface Object        returnam; }}

Configuration file Contents

Classpath=factory.unit.cat

Test class

ImportFactory.unit.Animal;Importfactory.unit.Factory; Public classFactorymodetest {//test function, caller     Public Static voidMain (string[] args) {//TODO auto-generated Method Stub//get an instance of the factoryFactory FC =factory.getfactory (); //invokes the method that obtains the interface object, obtains the interface objectAnimal Testanimal =Fc.getinterface (); //methods to invoke an interfaceTestanimal.eatfood (); }}

Results:

When the configuration file is entered Classpath=factory.unit.cat The result is that the cat eats fish

When the configuration file is entered Classpath=factory.unit.dog the dog eats meat.

So when we change the product, we just need to make changes to the configuration file, no need to re-modify the code, change the New Cat () to New Dog (), which facilitates later modification and maintenance.

Examples of Java reflection and factory pattern implementations

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.