An article with you in-depth understanding of java reflection mechanism

reflection

Reflection (reflection) is one of the features of the Java programming language, which allows Java programs running on the inspection itself, or "self-examination", also called "introspection." Reflection is very powerful, it can even direct operating procedures of private property. We have to learn in front of a concept, can only access private class interior, and exterior is not enough, but this provision is reflected blatant broken.

Like a mirror reflection, it can obtain all the information in a runtime class can be defined obtain any information (including member variables, members of the method, configuration, etc.), and may be manipulated class fields, methods, and other constructors section.

Why reflection:

Our good new User (); not very good, why go to create objects by reflecting it? Then I want to ask you a question, why do you want to go to a restaurant? For example: We eat a steak dinner, if we ourselves created, what had to manage.

Benefit is what I do every step is very clear, the downside is what had to achieve their own, it is not exhausted. Cattle delivery tube you, eat what you tube, you tube slaughter, transport you tube, you tube refrigeration, cooking your pipe, tube and serve you. Take cooking, you can have a chef to do good?

then what should we do? There is a saying that good, professional thing to do professional people, keeping to the farmers, slaughter to the executioner, cooking to the chef. Then we doing it?

We took the direct cross legs to eat enough. Furthermore, the hotel put things well, not thrown on the ground, we pick up the eat, that's not all to the primitive. then what should we do? Very simple to do things in a container of it, such as the steak on a plate.

In the developed world there, spring is the professional organization that helps us to create an object, the managed object. We are not new objects, you can get beans directly from the container spring provided. Beans bottom is actually a Map <String, Object>, to finally get through getBean ( "user"). This one core to achieve is to use reflective technology.

A summary, not a class you create is your colleague or direct a third-party company, then you want to or have to call the underlying functionality of this class, you need reflective technology. A little abstract, do not worry, we have to be the case, you will immediately clear.

Class class object reflector

  • ( "Full path type") the Class.forName;
  • .Class class name
  • Object .getClass ();

Common method

  • Gets the package names, class names
  • getPackage().getName()//包名
  • getSimpleName()//类名
  • getName () // full class name

! ! Member variable definition information

  • getFields () variables // Get all public member variables, including inherited
  • getDeclaredFields () // get this class definition of member variables, including private, does not include inherited variables
  • getField (variable name)
  • getDeclaredField (variable name)

! ! Constructor definition information

  • getConstructor (parameter type list) // constructor disclosed obtained
  • getConstructors () // get all constructors disclosed
  • getDeclaredConstructors () // get all the construction methods, including private
  • getDeclaredConstructor(int.class, String.class)

Method definition information

  • getMethods () method // get all the visible methods, including inherited
  • getMethod (method name, parameter type list)
  • getDeclaredMethods () // how to obtain the class definition, including private, not include inherited methods
  • getDeclaredMethod (method name, int.class, String.class)

Examples of new reflection

  • the newInstance (); // constructor with no arguments performed
  • the newInstance (. 6, "ABC"); // configuration parameters have performed
  • getConstructor (int.class, String.class); constructor parameter containing // perform configuration, obtaining

Call to a member variable reflection

  • getDeclaredField (variable name); // get variables
  • setAccessible (to true); // allow access to the private members
  • set (example, value); // variable assignment specified instance, a static variable, a first parameter to null
  • get (Example); value of a variable accessible // specified instance, a static variable, a first parameter to null

Reflection member method call

  • Acquisition method
  • Method m = c.getDeclaredMethod (method name, parameter type list);
  • m.setAccessible (to true); // make private methods allow to be called
  • m.invoke (example, parameter data); // make an instance of the specified method to perform the

Reflected Application

Create a class

class Student{
    String name="jack";
    int age=20;    
    public Student() {
       System.out.println("无参构造");
    }
    public Student(String name) {
       this.name=name;
       System.out.println("含参构造"+name);
    }    
    public void show(int a) {
       System.out.println("show()..."+a);
    }    
}

Get a class object

private static void method() throws Exception {
   Class clazz = Student.class;
   Class<?> clazz2 = Class.forName("seday15.Student");
   Class clazz3 = new Student().getClass();       
   System.out.println(clazz.getName());
   System.out.println(clazz2.getName());
   System.out.println(clazz3.getName());
}

Obtaining construction method

private static void method3(Class clazz) {
       Constructor[] cs = clazz.getDeclaredConstructors();
       for (Constructor c : cs) {
           String name = clazz.getSimpleName();
           System.out.println(name);           
           Class[] cs2 = c.getParameterTypes();//参数
           System.out.println(Arrays.toString(cs2));           
       }
 }

Acquiring member method

private static void method4(Class clazz) {
     Method[] ms = clazz.getMethods();
       for (Method m : ms) {
           String name = m.getName();
           System.out.println(name);           
           Class<?>[] cs = m.getParameterTypes();
           System.out.println(Arrays.toString(cs));
       }
}

Acquiring member variables

  private static void method2(Class clazz) {
       Field[] fs = clazz.getFields();//获取public的属性
       for (Field f : fs) {
           String name = f.getName();
           String tname = f.getType().getSimpleName();
           System.out.println(name);
           System.out.println(tname);
       }
}

Let us talk about violence reflects what is violence reflected it? There are many methods in Java objects and for safety considerations, it is encapsulated in the class. Often these proprietary methods and objects can only be invoked within the class, outside of class for it, are hidden, invisible. In order to obtain these objects and proprietary method of operating the external class, it can be implemented using a reflection violent manner. In simple terms it refers to can be private property or method program, violence to obtain resources through reflection technology.

Creating the Person class

class Person{    
    private String name="jack";
    private int age = 30;    
    private void show(int[] a) {
       System.out.println("show()..."+Arrays.toString(a));
    }
    private void test() {
       System.out.println("test()...");
    }
}

Look at the example above, member variables and member methods are private, so how will we get the value of it? Let's test

package seday16new;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectPerson {
    public static void main(String[] args) throws Exception {
       Class<?> clazz = Class.forName("seday16new.Person");
//     method(clazz);//隐私属性
       method2(clazz);//执行方法
    }
    
    private static void method2(Class<?> clazz) throws Exception {
       Method m = clazz.getDeclaredMethod("show", int[].class);
       Object obj = clazz.newInstance();
       m.setAccessible(true);//方法隐私可见
       m.invoke(obj, new int[]{1,2,3});//执行
    } 
    
    private static void method(Class clazz) throws Exception {
       Field f = clazz.getDeclaredField("name");
       System.out.println(f.getType().getName());
       f.setAccessible(true);//属性隐私可见
       Object obj = clazz.newInstance();
//     f.set(obj, "rose");//设置值
       System.out.println(f.get(obj));//获取值   
              
       //---所有属性
       Field[] fs = clazz.getDeclaredFields();
       for (Field ff : fs) {
           System.out.println(ff);
           ff.setAccessible(true);//暴力反射
           System.out.println(ff.get(obj));
       }       
    }    
}

result:

  • Obtain and modify the value of private property
  • Acquisition and implementation of private methods

Published 36 original articles · won praise 13 · views 1057

Guess you like

Origin blog.csdn.net/weixin_44598691/article/details/104952448