Simple use of Java's reflection mechanism

Table of contents

1. Definition

2. Purpose

3. Reflection basic information

4. Reflection related classes

5. Reflection Example

6. Advantages and Disadvantages of Reflection


1. Definition

        Java’s reflection mechanism isthe runtime state, which can be called through reflection Properties and methods, Private properties and methods can also be called, orModify them.


2. Purpose

        (1) During the development process of third-party applications, we often encounterprivate member variables and methodsor Only open to system applications, this formula can use the reflection mechanism to get these private member variables and methods.

(2), opening various types of universal frames.


3. Reflection basic information

        Many objects in Java programs will have two types at runtime, one is compile-time type, and the other is< a i=3>Runtime type, for example:

Person p = new Student(); In this case, the type of p is Person at compile time and Student at runtime. The program needs to know its type at runtime. Types and objects,Java's reflection program can determine which category the object and class belongs to.


4. Reflection related classes

(1) Obtain class-related methods

(2) Methods to obtain attributes in a class

(3) Methods to obtain annotations in classes

(4) Obtain the constructor-related methods in the class

(5) Methods to obtain methods in classes


5. Examples of reflection

(1) Three ways to obtain class objects, the first one is the most commonly used

We are creating a package demo1 and creating a Student class inside it, as shown in the figure

Student class code:

class Student{
    //私有属性name
    private String name = "bit";
    //公有属性age
    public int age = 18;
    //不带参数的构造方法
    public Student(){
        System.out.println("Student()");
    }
    private Student(String name,int age) {
        this.name = name;
        this.age = age;
        System.out.println("Student(String,name)");
    }
    private void eat(){
        System.out.println("i am eat");
    }
    public void sleep(){
        System.out.println("i am sleep");
    }
    private void function(String str) {
        System.out.println(str);
    } @
            Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Code example:

public class Test {
    public static void main(String[] args) {
        //获得class对象的三种方式
        //第一种
        try {
            Class.forName("demo1.Student");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //第二种
        Class<?> c2 = Student.class;
        //第三种
        Student student = new Student();
        Class c3 = student.getClass();
    }
}

(2) Use of reflection

(1) Create objects

                Code example:
public class Test {
    public static void main(String[] args) {
        //获得class对象的三种方式
        //第一种
        try {
            Class.forName("demo1.Student");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //第二种
        Class<?> c2 = Student.class;
        //第三种
        Student student = new Student();
        Class c3 = student.getClass();
    }
}
        Get the object of Student class
//第一种
        try {
            Class<?>ClassStudent = Class.forName("demo1.Student");
            Student student = (Student)ClassStudent.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

(2) Reflection private construction method

             Code example:
    public static void reflectNewInstance() {
        //反射私有的构造方法
        try {
            //先拿到一个类
            Class<?> classStudent = Class.forName("demo1.Student");
            //调用构造方法
            Constructor<?> constructor = classStudent.getDeclaredConstructor(String.class, int.class);
            //私有的属性name需要你确认才能更改
            constructor.setAccessible(true);
            Student student = (Student) constructor.newInstance("xiaoming", 15);
            System.out.println(student);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

Phenomenon after calling this code:

(3) Reflection private attributes

                Code example:

                

public static void reflectPrivateField() {
        //反射私有属性
        try {
            Class<?> classStudent = Class.forName("demo1.Student");
            Field field = classStudent.getDeclaredField("name");
            field.setAccessible(true);
            Student student = (Student)classStudent.newInstance();
            field.set(student, "caocao");
            System.out.println(student);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

Phenomenon after calling this code:

(4) Reflection private method

                Code example:
public static void reflectPrivateMethod() {
        //反射私有方法
        try {
            Class<?> classStudent = Class.forName("demo1.Student");
            Method method = classStudent.getDeclaredMethod("function");
            method.setAccessible(true);

            Student student = (Student)classStudent.newInstance();

            method.invoke(student, "我是一个反射参数");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

6. Advantages and Disadvantages of Reflection

Advantages: 1. Member variables or methods of any class can be called. For any object, its methods can be called, and encapsulation will not work.

           ​ ​ ​ 2. Applied to many popular frameworks (Struts, Hibernate, Spring, etc.).

           3. Enhance the flexibility and scalability of the program.

Disadvantages: 1. Efficiency issues. Using reflection programs will lead to low program efficiency.

           ​ ​ ​ 2. Because the function is too powerful, it is more troublesome to maintain, and the reflection code is also more complex than the ordinary code.


You’ve all seen this, give it a thumbs up and go away, thank you, thank you, thank you!

Guess you like

Origin blog.csdn.net/cool_tao6/article/details/134013942