Java basics: reflection mechanism

1. What is reflection:

      Reflection is one of the characteristics of Java. It is a mechanism for indirect manipulation of the target object. The core is that the JVM dynamically loads the class when it is running, and for any class, you can know all the attributes and methods of this class, and call the method/ To access attributes, you don't need to know who the running object is at compile time in advance. It allows the running Java program to obtain class information and can manipulate the internal properties of the class or object. The types of objects in the program are generally determined during compilation. When our program is running, some classes may need to be dynamically loaded. These classes are not used before, so they are not loaded into the jvm. At this time, Using the Java reflection mechanism, you can dynamically create an object and call its properties at runtime, and it is loaded as needed at runtime.

Two: the role of reflection

  • Judge the class to which any object belongs at runtime ;

  • Construct an object of any class at runtime ;

  • Judge the member variables and methods of any class at runtime ;

  • Call any object's method at runtime ;

Three, the advantages and disadvantages of reflection:

1. Advantages: Using reflection, we can obtain various contents of the class at runtime and perform decompilation. For Java, a language that is compiled and then run, it is convenient for us to create flexible codes. These codes can be used in Run-time assembly, no need to link the source code between components, easier to achieve object-oriented.

2. Disadvantages: (1) Reflection consumes certain system resources. Therefore, if you do not need to dynamically create an object, then you do not need to use reflection;

(2) The permission check can be ignored when the reflection method is called, so it may destroy the encapsulation and cause security problems.

Fourth, the commonly used classes of reflection mechanism:

Java.lang.Class;

Java.lang.reflect.Constructor;

Java.lang.reflect.Field;

Java.lang.reflect.Method;

Java.lang.reflect.Modifier;

Five: the realization of reflection

We know that to use a class, we must first load it into the virtual machine to generate a Class object. This class object saves all the information of this class.
The realization of the reflection mechanism is to obtain this Class object, through the Class object to access the metadata of the class, the object and the runtime data.
There are three ways to obtain the Class object of a class: Class.forName(String className), className.class, instance object.getClass();

Six: API involved in reflection

Reflection first obtains the Class object; then obtains the Method and Field classes; finally, performs specific method calls or attribute accesses through the Method and Field classes.
1: Obtain information such as the class name of the object's class at runtime

对象名.getClass().getName();

2: Create a class object through the reflection mechanism (three methods)

class1 = Class.forName(className);
class2 = 对象名.getClass();
class3 = 对象名.class;

3: At runtime, obtain your own parent class information by creating a class object

Class<?> clazz = Class.forName(当前类);
Class<?> parentClass = clazz.getSuperclass();
parentClass.getName();//获得父类名

4: Create an object of a class through the reflection mechanism

1:反射创建class对象(见上面)
2:Classname 对象=classname.newInstance(参数);

5: Get all the methods of the class, stored in an array

//创建class对象
Class<?> clazz = Class.forName(ClassName);
// 返回声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。 
Method[] getDeclaredMethods();
//返回可被访问的公共方法      
Method method[] = clazz.getMethods();

6: Get all the fields of the class and store them in an array

Class<?> clazz = Class.forName(classname);
// 取得本类已声明的所有字段,包括私有的、保护的
Field[] field = clazz.getDeclaredFields();
// 取得本类中可访问的所有公共字段
Field[] filed1 = clazz.getFields();

7: Operate a certain attribute of the class/object (including private)

Class<?> clazz = Class.forName(classname);
//返回一个 Field 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明字段。 包括公共、私有、保护的字段。
Field field = clazz.getDeclaredField(字段名);
//禁用Java权限修饰符的作用,无视方法权限限制进行访问
field.setAccessible(true);
// void set(Object obj, Object value) 将指定对象变量上此 Field 对象表示的字段设置为指定的新值。           
field.set(该类的一个对象, 字段值);

8: Call a method of the class/object (including private)

Class<?> clazz = Class.forName(classname);

// Method getMethod(String name, Class<?>... parameterTypes) 
//返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。
//获取一个公有函数
Method method = clazz.getMethod(方法名,参数类型);
//调用具体某个实例对象的这个公有方法
method.invoke(实例对象,参数值);

// Method getDeclaredMethod(String name, Class<?>... parameterTypes) 
//返回一个 Method 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明方法。 包括私有、保护、公有方法

//获取一个私有函数
Method private_method=class.getDeclaredMethod(函数名,参数类型);

//禁用Java权限限定符的作用,使私有函数可访问
private_method.setAccessible(true);

//调用具体实例对象的这个方法
private_method.invoke(实例对象,参数);

example:

Student class: a total of six construction methods

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);
    }
}

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):获取"某个构造方法"可以是私有的,或受保护、默认、公有;
 * 		3).调用构造方法:
 * 			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('男');
    }
}

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)
姓名:男

Process finished with exit code 0

StudentNew class gets member variables and calls

package fanshe;

public class StudentNew {
    public StudentNew(){

    }
    //**********字段*************//
    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;


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.StudentNew");
        //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 = "刘德华"
        //验证
        StudentNew stu = (StudentNew)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);

    }
}

Output

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

StudentTwo get member method and call

package fanshe;

public class StudentTwo {
    //**************成员方法***************//
    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;

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.StudentTwo");
        //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);
    }
}

Output

***************获取所有的”公有“方法*******************
public void fanshe.StudentTwo.show1(java.lang.String)
public final void java.lang.Object.wait() throws java.lang.InterruptedException
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 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.StudentTwo.show1(java.lang.String)
void fanshe.StudentTwo.show3()
private java.lang.String fanshe.StudentTwo.show4(int)
protected void fanshe.StudentTwo.show2()
***************获取公有的show1()方法*******************
public void fanshe.StudentTwo.show1(java.lang.String)
调用了:公有的,String参数的show1(): s = 刘德华
***************获取私有的show4()方法******************
private java.lang.String fanshe.StudentTwo.show4(int)
调用了,私有的,并且有返回值的,int参数的show4(): age = 20
返回值:abcd

Process finished with exit code 0

 

Guess you like

Origin blog.csdn.net/PrisonJoker/article/details/105321638