Reflection type

First, what is reflection? ?

1, JAVA reflection is in the operating state, corresponding to any class, are able to know all the properties and methods of this class; for any one object, it can invoke a method of any of; the information acquired in this state and the dynamic invocation function method object is called reflection mechanism of Java language.

2, simply, reflection refers to the program itself can obtain information at runtime. In java, just give the name of a given class, then you can get all the information to the class through reflection. Including their access modifier, the parent class, all of the information interfaces, properties and methods of implementation, and create objects at runtime, modify the properties (including private), call the method (including private).

Second,    why should reflection? Not directly create objects on it yet, which involves the dynamic and static concept

a) static compiler: determined at compile-time type, binding objects, i.e. by Student stu = new Student ( "zhangsan", 20);

b) dynamic compilation: determine the type of running, binding objects. To maximize the flexibility of dynamic compilation of java, polymorphism reflects the application, to reduce the coupling between classes.

            Class.forName(“com.mysql.jdbc.Driver.class”).newlnstance();

c) the advantages of reflection is that you can create objects and dynamic compilation, reflecting the great flexibility, especially the development of J2EE.

d) The disadvantage is performance impact, using essentially a reflection explaining the operation, such operations are always slower than the same operation performed directly.

Third, the object is generated in two ways

1, by way of new objects

   

2, by reflection

  

         Note: forName ( "package name of the class name."), And the method supports only the default constructor of an object.

       To call the constructor of the class with parameters, it is used in the following manner:

     

 

      This method can be generated by any object class constructor call class, with the parameters passed to the constructor matches. (Note: is the type of incoming Class object)

      Tip: When a class constructor is defined as a private, not outside the class described new class of objects.

 

Four, three ways to get the class object of the class

 1,Class   c = Student .class;

      This method can only Student Class object class is loaded into memory, it does not initialize.

 

    Note: use the class name .class, because the object has not created

 2, Class c2 = Class.forName ( "package name class name of class to be loaded.");

     The class loaded in, and memory allocation and initialization assignment

     At this time, by making the Class object methods, and the package name. Class name to load the class assigned to the process

   

  3.Student student = new Student ( "Joe Smith", 20, 'M', "Xi'an Technological University");

     Class  c3=student.getClass();

    Classes loaded in, and initialize the memory allocation and assignment, class instance also generated at this time.

    Note: At this time, is loaded to the class object is generated by getClass ().

 

Fifth, by reflecting the acquired class constructor / variables / Method

1, method

 

 

 

 

 2, variable

 

 

 

 

3. Constructor (ibid)

 

Sixth, by private members reflection access to the class (must first new objects)

    When a class property or method is defined as a private, this time by way of the new target is not accessible, but by means of reflection, but can be accessed.

1, the method invoked by reflection.

      The first step: Get Class object class:

                    Student student = new Student ( "Joe Smith", 20, 'M', "Xi'an Technological University");

                    Class c=student.getClass();

      Step Two: Get variable / method:

            Methods: Method, Method, = c.getDeclaredMethod ( "Sing"); // The name of the method to get incoming

           Variables: Field, Field, = c.getDeclaredField ( "Age"); // variable to get the name of the incoming

     The third step: access settings to access the variable or method

                    field.setAccessible(true);

     Step Four: operation (access to the appropriate member of attention when using this method, the object should first pass, pass in parameters)

                     newInstance - construct an object
                       invoke - members of the method call
                       set - member variables

 

 

 

 

 VII Application examples

     Prior to the development of model programs for always stressed: to minimize coupling, while reducing the use of best practices coupled interface, but even using the keyword new interface is also not escape, so this is actually new is the key culprit causing coupling.

Example 1: factory design pattern

 1 package Factory_demo;
 2 
 3 interface Fruit {
 4     public void eat() ;
 5 }
 6 class Apple implements Fruit {
 7     public void eat() {
 8         System.out.println("吃苹果。");
 9     };
10 }
11 class Factory {
12     public static Fruit getInstance(String className) {
13         if("apple".equals(className)){
14             return new Apple() ;
15         }
16         return null;
17     }
18 }
19 public class Demo {
20     public static void main(String[] args) {
21         Fruit f = Factory.getInstance("apple") ;
22         f.eat() ;
23     }
24 }

以上为之前所编写最简单的工厂设计模式,但是在这个工厂设计模式之中有一个最大的问题:如果现在接口的子类增加了,那么工厂类肯定需要修改,这是它所面临的最大问题,而这个最大问题造成的关键性的病因是new,那么如果说现在不使用关键字new了,变为了反射机制呢?

反射机制实例化对象的时候实际上只需要“包.类”就可以,于是根据此操作,修改工厂设计模式。

 1 package reflection_demo1;
 2 
 3 interface Fruit {
 4     public void eat() ;
 5 }
 6 class Apple implements Fruit {
 7     public void eat() {
 8         System.out.println("吃苹果。");
 9     };
10 }
11 class Orange implements Fruit {
12     public void eat() {
13         System.out.println("吃橘子。");
14     };
15 }
16 
17 class Factory {
18     public static Fruit getInstance(String className) {
19         Fruit f = null;
20         try{
21             f = (Fruit) Class.forName(className).newInstance() ;
22         } catch(Exception e) {
23             e.printStackTrace();
24         }
25         return f ;
26     }
27 }
28 
29 public class Demo {
30     public static void main(String[] args) {
31         Fruit f = Factory.getInstance("reflection_demo1.Orange") ;   //传参数 包名.类名
32         f.eat() ;
33     }
34 }

 发现,这个时候即使增加了接口的子类,工厂类照样可以完成对象的实例化操作,这个才是真正的工厂类,可以应对于所有的变化。如果单独从开发角度而言,与开发者关系不大,但是对于日后学习的一些框架技术这个就是它实现的命脉,在日后的程序开发上,如果发现操作的过程之中需要传递了一个完整的“包.类”名称的时候几乎都是反射机制作用。

 

Guess you like

Origin www.cnblogs.com/ljl150/p/11786077.html