Java Basics - Reflection

Please indicate the source for reprinting: https://blog.csdn.net/sinat_38259539/article/details/71799078
Reflection is the soul of framework design (precondition for use: You must first get the Class of the represented bytecode, and the Class class is used for Represents a .class file (bytecode))

An overview of reflection

The JAVA reflection mechanism is that in the running state, for any class, you can know all the properties and methods of the class; for any object, you can call any of its methods and properties; this dynamically obtained information and dynamic call The function of the method of the object is called the reflection mechanism of the java language.
To dissect a class, you must first obtain the bytecode file object of the class. The anatomy uses the methods in the Class class. So first get the Class type object corresponding to each bytecode file.

The above summary is what is reflection
Reflection is to map various components in java classes into Java objects one by one

For example, a class has information such as member variables, methods, construction methods, packages, etc. Using reflection technology, a class can be dissected, and each component can be mapped into an object. (Actually: these member methods, constructors, and joining classes in a class are described by a class)

The picture shows the normal loading process of a class: the principle of reflection is related to the class object.
Familiarize yourself with loading time: The origin of the Class object is to read the class file into memory and create a Class object for it.

write picture description here

Among them, the Class object is very special. Let's take a look at the Class class first.

2. View the detailed api of the Class class in java (API of 1.7)

write picture description here

Class Instances represent classes and interfaces in a running Java application. That is, there are more than N instances in the jvm, and each class has the Class object. (including primitive data types)
Class has no public constructors. Class objects are automatically constructed by the Java virtual machine when the class is loaded and by calling the defineClass method in the class loader. That is, we don't need to deal with the creation ourselves, the JVM has already created it for us.

There is no public constructor, 64 methods are too many. Which one is used below will be explained in detail.

write picture description here

3. The use of reflection (the Student class is used here for demonstration)

Write a Student class first.

1. Three ways to obtain Class objects
  • Object ——> getClass();
  • Any data type (including primitive data types) has a "static" class attribute
  • Through the static method of the Class class: forName (String className) (commonly used)

Among them, 1.1 is because of the getClass method in the Object class, because all classes inherit the Object class. So call the Object class to get

write picture description here

package fanshe;  
/** 
 * 获取Class对象的三种方式 
 * 1 Object ——> getClass(); 
 * 2 任何数据类型(包括基本数据类型)都有一个“静态”的class属性 
 * 3 通过Class类的静态方法:forName(String  className)(常用) 
 * 
 */  
public class Fanshe {  
    public static void main(String[] args) {  
        //第一种方式获取Class对象    
        Student stu1 = new Student();//这一new 产生一个Student对象,一个Class对象。  
        Class stuClass = stu1.getClass();//获取Class对象  
        System.out.println(stuClass.getName());  

        //第二种方式获取Class对象  
        Class stuClass2 = Student.class;  
        System.out.println(stuClass == stuClass2);//判断第一种方式获取的Class对象和第二种方式获取的是否是同一个  

        //第三种方式获取Class对象  
        try {  
            Class stuClass3 = Class.forName("fanshe.Student");//注意此字符串必须是真实路径,就是带包名的类路径,包名.类名  
            System.out.println(stuClass3 == stuClass2);//判断三种方式是否获取的是同一个Class对象  
        } catch (ClassNotFoundException e) {  
            e.printStackTrace();  
        }  

    }  
}

Note: During runtime, a class, only one Class object is generated.

The third method is commonly used in the third method. The first object has all the objects and what to do with reflection. The second type of package that needs to import the class, the dependency is too strong, and the compilation error will be thrown if the package is not imported. Generally the third, a string can be passed in or written in the configuration file and other methods.

2. Obtain the constructor through reflection and use:

student class:

package fanshe;  

public class Student {  

    //---------------构造方法-------------------  
    //(默认的构造方法)  
    Student(String str){  
        System.out.println("(默认)的构造方法 s = " + str);  
    }  

    //无参构造方法  
    public Student(){  
        System.out.println("调用了公有、无参构造方法执行了。。。");  
    }  

    //有一个参数的构造方法  
    public Student(char name){  
        System.out.println("姓名:" + name);  
    }  

    //有多个参数的构造方法  
    public Student(String name ,int age){  
        System.out.println("姓名:"+name+"年龄:"+ age);//这的执行效率有问题,以后解决。  
    }  

    //受保护的构造方法  
    protected Student(boolean n){  
        System.out.println("受保护的构造方法 n = " + n);  
    }  

    //私有构造方法  
    private Student(int age){  
        System.out.println("私有的构造方法   年龄:"+ age);  
    }  

}  

There are a total of 6 construction methods;

Test class:
package fanshe;  

import java.lang.reflect.Constructor;  


/* 
 * 通过Class对象可以获取某个类中的:构造方法、成员变量、成员方法;并访问成员; 
 *  
 * 1.获取构造方法: 
 *      1).批量的方法: 
 *          public Constructor[] getConstructors():所有"公有的"构造方法 
            public Constructor[] getDeclaredConstructors():获取所有的构造方法(包括私有、受保护、默认、公有) 

 *      2).获取单个的方法,并调用: 
 *          public Constructor getConstructor(Class... parameterTypes):获取单个的"公有的"构造方法: 
 *          public Constructor getDeclaredConstructor(Class... parameterTypes):获取"某个构造方法"可以是私有的,或受保护、默认、公有; 
 *       
 *          调用构造方法: 
 *          Constructor-->newInstance(Object... initargs) 
 */  
public class Constructors {  

    public static void main(String[] args) throws Exception {  
        //1.加载Class对象  
        Class clazz = Class.forName("fanshe.Student");  


        //2.获取所有公有构造方法  
        System.out.println("**********************所有公有构造方法*********************************");  
        Constructor[] conArray = clazz.getConstructors();  
        for(Constructor c : conArray){  
            System.out.println(c);  
        }  


        System.out.println("************所有的构造方法(包括:私有、受保护、默认、公有)***************");  
        conArray = clazz.getDeclaredConstructors();  
        for(Constructor c : conArray){  
            System.out.println(c);  
        }  

        System.out.println("*****************获取公有、无参的构造方法*******************************");  
        Constructor con = clazz.getConstructor(null);  
        //1>、因为是无参的构造方法所以类型是一个null,不写也可以:这里需要的是一个参数的类型,切记是类型  
        //2>、返回的是描述这个无参构造函数的类对象。  

        System.out.println("con = " + con);  
        //调用构造方法  
        Object obj = con.newInstance();  
    //  System.out.println("obj = " + obj);  
    //  Student stu = (Student)obj;  

        System.out.println("******************获取私有构造方法,并调用*******************************");  
        con = clazz.getDeclaredConstructor(char.class);  
        System.out.println(con);  
        //调用构造方法  
        con.setAccessible(true);//暴力访问(忽略掉访问修饰符)  
        obj = con.newInstance('男');  
    }  

}  
Background output:
**********************所有公有构造方法*********************************  
public fanshe.Student(java.lang.String,int)  
public fanshe.Student(char)  
public fanshe.Student()  
************所有的构造方法(包括:私有、受保护、默认、公有)***************  
private fanshe.Student(int)  
protected fanshe.Student(boolean)  
public fanshe.Student(java.lang.String,int)  
public fanshe.Student(char)  
public fanshe.Student()  
fanshe.Student(java.lang.String)  
*****************获取公有、无参的构造方法*******************************  
con = public fanshe.Student()  
调用了公有、无参构造方法执行了。。。  
******************获取私有构造方法,并调用*******************************  
public fanshe.Student(char)  
姓名:男  
Call method:

1. Get the constructor:

  • Bulk methods:
    public Constructor[] getConstructors(): all "public" constructors
    public Constructor[] getDeclaredConstructors(): get all constructors (including private, protected, default, public)

  • Get a single method and call:
    public Constructor getConstructor(Class... parameterTypes): Get a single "public" constructor:
    public Constructor getDeclaredConstructor(Class... parameterTypes): Get "a constructor" that can be private, or subject to protected, default, public;

  • Call the constructor:
    Constructor–>newInstance(Object… initargs)

2. newInstance is a method of the Constructor class (the class that manages the constructor)

  • The interpretation of the api is:
    newInstance(Object… initargs) Use the constructor represented by this Constructor object to create a new instance of the declared class of the constructor, and initialize the instance with the specified initialization parameters. Its return value is of type T, so newInstance is a new instance object of the declaring class with a constructor created. and call for it.
3. Get member variables and call

student class:

package fanshe.field;  

public class Student {  
    public Student(){  

    }  
    //**********字段*************//  
    public String name;  
    protected int age;  
    char sex;  
    private String phoneNum;  

    @Override  
    public String toString() {  
        return "Student [name=" + name + ", age=" + age + ", sex=" + sex  
                + ", phoneNum=" + phoneNum + "]";  
    }  
}

Test class:

package fanshe.field;  
import java.lang.reflect.Field;  
/* 
 * 获取成员变量并调用: 
 *  
 * 1.批量的 
 *      1).Field[] getFields():获取所有的"公有字段" 
 *      2).Field[] getDeclaredFields():获取所有字段,包括:私有、受保护、默认、公有; 
 * 2.获取单个的: 
 *      1).public Field getField(String fieldName):获取某个"公有的"字段; 
 *      2).public Field getDeclaredField(String fieldName):获取某个字段(可以是私有的) 
 *  
 *   设置字段的值: 
 *      Field --> public void set(Object obj,Object value): 
 *                  参数说明: 
 *                  1.obj:要设置的字段所在的对象; 
 *                  2.value:要为字段设置的值; 
 *  
 */  
public class Fields {  

        public static void main(String[] args) throws Exception {  
            //1.获取Class对象  
            Class stuClass = Class.forName("fanshe.field.Student");  
            //2.获取字段  
            System.out.println("************获取所有公有的字段********************");  
            Field[] fieldArray = stuClass.getFields();  
            for(Field f : fieldArray){  
                System.out.println(f);  
            }  
            System.out.println("************获取所有的字段(包括私有、受保护、默认的)********************");  
            fieldArray = stuClass.getDeclaredFields();  
            for(Field f : fieldArray){  
                System.out.println(f);  
            }  
            System.out.println("*************获取公有字段**并调用***********************************");  
            Field f = stuClass.getField("name");  
            System.out.println(f);  
            //获取一个对象  
            Object obj = stuClass.getConstructor().newInstance();//产生Student对象--》Student stu = new Student();  
            //为字段设置值  
            f.set(obj, "刘德华");//为Student对象中的name属性赋值--》stu.name = "刘德华"  
            //验证  
            Student stu = (Student)obj;  
            System.out.println("验证姓名:" + stu.name);  


            System.out.println("**************获取私有字段****并调用********************************");  
            f = stuClass.getDeclaredField("phoneNum");  
            System.out.println(f);  
            f.setAccessible(true);//暴力反射,解除私有限定  
            f.set(obj, "18888889999");  
            System.out.println("验证电话:" + stu);  

        }  
    }

Background output:

************获取所有公有的字段********************  
public java.lang.String fanshe.field.Student.name  
************获取所有的字段(包括私有、受保护、默认的)********************  
public java.lang.String fanshe.field.Student.name  
protected int fanshe.field.Student.age  
char fanshe.field.Student.sex  
private java.lang.String fanshe.field.Student.phoneNum  
*************获取公有字段**并调用***********************************  
public java.lang.String fanshe.field.Student.name  
验证姓名:刘德华  
**************获取私有字段****并调用********************************  
private java.lang.String fanshe.field.Student.phoneNum  
验证电话:Student [name=刘德华, age=0, sex=  

It can be seen that:

When calling a field, you need to pass two parameters:
// Generate a Student object – "Student stu = new Student();
Object obj = stuClass.getConstructor().newInstance();
Set the value for the field
// is the name in the Student object Attribute assignment – ​​"stu.name = "Andy Lau"
f.set(obj, "Andy Lau");

The first parameter: the object to be passed in, the second parameter: the actual parameter to be passed in

4. Get the member method and call it

student class:

package fanshe.method;  

public class Student {  
    //**************成员方法***************//  
    public void show1(String s){  
        System.out.println("调用了:公有的,String参数的show1(): s = " + s);  
    }  
    protected void show2(){  
        System.out.println("调用了:受保护的,无参的show2()");  
    }  
    void show3(){  
        System.out.println("调用了:默认的,无参的show3()");  
    }  
    private String show4(int age){  
        System.out.println("调用了,私有的,并且有返回值的,int参数的show4(): age = " + age);  
        return "abcd";  
    }  
} 

Test class:

package fanshe.method;  

import java.lang.reflect.Method;  

/* 
 * 获取成员方法并调用: 
 *  
 * 1.批量的: 
 *      public Method[] getMethods():获取所有"公有方法";(包含了父类的方法也包含Object类) 
 *      public Method[] getDeclaredMethods():获取所有的成员方法,包括私有的(不包括继承的) 
 * 2.获取单个的: 
 *      public Method getMethod(String name,Class<?>... parameterTypes): 
 *                  参数: 
 *                      name : 方法名; 
 *                      Class ... : 形参的Class类型对象 
 *      public Method getDeclaredMethod(String name,Class<?>... parameterTypes) 
 *  
 *   调用方法: 
 *      Method --> public Object invoke(Object obj,Object... args): 
 *                  参数说明: 
 *                  obj : 要调用方法的对象; 
 *                  args:调用方式时所传递的实参; 

): 
 */  
public class MethodClass {  

    public static void main(String[] args) throws Exception {  
        //1.获取Class对象  
        Class stuClass = Class.forName("fanshe.method.Student");  
        //2.获取所有公有方法  
        System.out.println("***************获取所有的”公有“方法*******************");  
        stuClass.getMethods();  
        Method[] methodArray = stuClass.getMethods();  
        for(Method m : methodArray){  
            System.out.println(m);  
        }  
        System.out.println("***************获取所有的方法,包括私有的*******************");  
        methodArray = stuClass.getDeclaredMethods();  
        for(Method m : methodArray){  
            System.out.println(m);  
        }  
        System.out.println("***************获取公有的show1()方法*******************");  
        Method m = stuClass.getMethod("show1", String.class);  
        System.out.println(m);  
        //实例化一个Student对象  
        Object obj = stuClass.getConstructor().newInstance();  
        m.invoke(obj, "刘德华");  

        System.out.println("***************获取私有的show4()方法******************");  
        m = stuClass.getDeclaredMethod("show4", int.class);  
        System.out.println(m);  
        m.setAccessible(true);//解除私有限定  
        Object result = m.invoke(obj, 20);//需要两个参数,一个是要调用的对象(获取有反射),一个是实参  
        System.out.println("返回值:" + result);  


    }  
}  

Console output:

***************获取所有的”公有“方法*******************  
public void fanshe.method.Student.show1(java.lang.String)  
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException  
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException  
public final void java.lang.Object.wait() throws java.lang.InterruptedException  
public boolean java.lang.Object.equals(java.lang.Object)  
public java.lang.String java.lang.Object.toString()  
public native int java.lang.Object.hashCode()  
public final native java.lang.Class java.lang.Object.getClass()  
public final native void java.lang.Object.notify()  
public final native void java.lang.Object.notifyAll()  
***************获取所有的方法,包括私有的*******************  
public void fanshe.method.Student.show1(java.lang.String)  
private java.lang.String fanshe.method.Student.show4(int)  
protected void fanshe.method.Student.show2()  
void fanshe.method.Student.show3()  
***************获取公有的show1()方法*******************  
public void fanshe.method.Student.show1(java.lang.String)  
调用了:公有的,String参数的show1(): s = 刘德华  
***************获取私有的show4()方法******************  
private java.lang.String fanshe.method.Student.show4(int)  
调用了,私有的,并且有返回值的,int参数的show4(): age = 20  
返回值:abcd  

It can be seen that:

// To call the specified method (all including private ones), you need to pass in two parameters, the first is the name of the method to call, and the second is the parameter type of the method, remember the type.
m = stuClass.getDeclaredMethod("show4", int.class);
System.out.println(m);
// Unlock private qualification
m.setAccessible(true);
// Takes two parameters, one is the object to call ( Obtained with reflection), one is the actual parameter
Object result = m.invoke(obj, 20);
System.out.println("return value: " + result);

In fact, the member method here: there is a word attribute in the model, which is the setter() method and the getter() method. There are also field components, which are explained in introspection.

5. Reflect the main method

student class:

package fanshe.main;  

public class Student {  

    public static void main(String[] args) {  
        System.out.println("main方法执行了。。。");  
    }  
}  

Test class:

package fanshe.main;  

import java.lang.reflect.Method;  

/** 
 * 获取Student类的main方法、不要与当前的main方法搞混了 
 */  
public class Main {  

    public static void main(String[] args) {  
        try {  
            //1、获取Student对象的字节码  
            Class clazz = Class.forName("fanshe.main.Student");  

            //2、获取main方法  
             Method methodMain = clazz.getMethod("main", String[].class);//第一个参数:方法名称,第二个参数:方法形参的类型,  
            //3、调用main方法  
            // methodMain.invoke(null, new String[]{"a","b","c"});  
             //第一个参数,对象类型,因为方法是static静态的,所以为null可以,第二个参数是String数组,这里要注意在jdk1.4时是数组,jdk1.5之后是可变参数  
             //这里拆的时候将  new String[]{"a","b","c"} 拆成3个对象。。。所以需要将它强转。  
             methodMain.invoke(null, (Object)new String[]{"a","b","c"});//方式一  
            // methodMain.invoke(null, new Object[]{new String[]{"a","b","c"}});//方式二  

        } catch (Exception e) {  
            e.printStackTrace();  
        }  


    }  
}

Console output:
The main method is executed. . .

6. Other uses of the reflection method - run the content of the configuration file through reflection

student class:

public class Student {  
    public void show(){  
        System.out.println("is show()");  
    }  
} 

The configuration file takes the txt file as an example (pro.txt):

className = cn.fanshe.Student  
methodName = show  

Test class:

import java.io.FileNotFoundException;  
import java.io.FileReader;  
import java.io.IOException;  
import java.lang.reflect.Method;  
import java.util.Properties;  

/* 
 * 我们利用反射和配置文件,可以使:应用程序更新时,对源码无需进行任何修改 
 * 我们只需要将新类发送给客户端,并修改配置文件即可 
 */  
public class Demo {  
    public static void main(String[] args) throws Exception {  
        //通过反射获取Class对象  
        Class stuClass = Class.forName(getValue("className"));//"cn.fanshe.Student"  
        //2获取show()方法  
        Method m = stuClass.getMethod(getValue("methodName"));//show  
        //3.调用show()方法  
        m.invoke(stuClass.getConstructor().newInstance());  

    }  

    //此方法接收一个key,在配置文件中获取相应的value  
    public static String getValue(String key) throws IOException{  
        Properties pro = new Properties();//获取配置文件的对象  
        FileReader in = new FileReader("pro.txt");//获取输入流  
        pro.load(in);//将流加载到配置文件对象中  
        in.close();  
        return pro.getProperty(key);//返回根据key获取的value值  
    }  
}  

Console output:
is show()

Requirement:
When we upgrade the system, instead of the Student class, we need to write a new Student2 class, then we only need to change the content of the pro.txt file. No need to change the code

Student2 class to replace:

public class Student2 {  
    public void show2(){  
        System.out.println("is show2()");  
    }  
}

The configuration file is changed to:

className = cn.fanshe.Student2  
methodName = show2  

Console output:
is show2();

7. Other uses of the reflection method - bypassing the generic check through reflection

Generics are used at compile time, and they are erased (disappeared) after compilation. So it is possible to bypass the generic check through reflection

Test class:

import java.lang.reflect.Method;  
import java.util.ArrayList;  

/* 
 * 通过反射越过泛型检查 
 *  
 * 例如:有一个String泛型的集合,怎样能向这个集合中添加一个Integer类型的值? 
 */  
public class Demo {  
    public static void main(String[] args) throws Exception{  
        ArrayList<String> strList = new ArrayList<>();  
        strList.add("aaa");  
        strList.add("bbb");  

    //  strList.add(100);  
        //获取ArrayList的Class对象,反向的调用add()方法,添加数据  
        Class listClass = strList.getClass(); //得到 strList 对象的字节码 对象  
        //获取add()方法  
        Method m = listClass.getMethod("add", Object.class);  
        //调用add()方法  
        m.invoke(strList, 100);  

        //遍历集合  
        for(Object obj : strList){  
            System.out.println(obj);  
        }  
    }  
}  

Console output:
aaa
bbb
100

This article on the basics of reflection is really good, thanks to the original author for sharing.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324893342&siteId=291194637