Getting started with Java Reflection, with detailed code examples

Posted by edontee on Thu, 21 Oct 2021 21:10:07 +0200

1. Basic concepts of reflection

You can get everything in a class by reflection:
1) Properties
2) parameterless construction method
3) parametric construction method
4) General method
Then tell me which step to use reflection?
1) First we will create a java file:.java file
2) The java file is then compiled:.class file
3) Use jvm to load the class file into memory through class loading.
At this point, all the java classes we started creating will exist in memory as Class classes, which will give you all the contents of the classes.
1) Class use encapsulating attributes:Field
2) Class use encapsulating construction methods: Constructor
3) Class use encapsulating common methods:

2. No-parameter construction using reflection operation

If we create a Person class, first we need to know three ways to get it:
1)Class c1 = Person.class;
2)Class c2 = new Person().getCLass();
3)Class c3 = Class.forName();

Second, in addition to using the new keyword, you can now use the newInstance method of the Class class to create new objects.
Person p = (Person) c3.newInstance();
An example code using a parameterless construct is as follows:
1) First create a Person class

package com.seleflearn;

public class Person {
    // Two attributes
    private String name;
    private int age;

    // non-parameter constructor
    public Person() {};

    // Parametric constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // General method
    @Override
    public String toString() {
        return this.name + "Age is:" + this.age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

2) Then create an instance through reflection and set attribute values for the instance

package com.seleflearn;

public class test1 {
    public static void main(String[] args) throws Exception{
        //Get Class
        Class c = Class.forName("com.seleflearn.Person");

        // Create an instance of Person using a parameterless construction method
        Person p = (Person) c.newInstance();

        // Set name and age
        p.setName("Zhang San");
        p.setAge(20);
        System.out.println(p.toString());
    }
}

The results are as follows:

/opt/java/jdk-16.0.2/bin/java -javaagent:/opt/idea-IC-212.5457.46/lib/idea_rt.jar=45811:/opt/idea-IC-212.5457.46/bin -Dfile.encoding=UTF-8 -classpath /home/koping/wxp/learn/java/java-web/day20211017/out/production/testReflection com.seleflearn.test4
 Zhang San's age is: 20

Process finished with exit code 0

3. Parameter construction using reflection operation

1) Get all the construction methods by getConstructors():
c.getConstructors();
2) Get the parametric construction method by getConstructor() method, get the parameter type of the parametric construction method, need to be passed as class
Constructor cs = c.getConstructor(String.class, int.class);
3) Examples can be created by a parametric construction method:
Person P = (Person) cs.newInstance (Zhang San, 20);

An example of creating and setting up an instance using a disabled construction method is as follows:

package com.seleflearn;

import java.lang.reflect.Constructor;

public class test2 {
    public static void main(String[] args) throws Exception{
        //Get Class
        Class c = Class.forName("com.seleflearn.Person");

        // Get the parametric construction method, get the parameter type of the parametric construction method, need to be passed as a class
        Constructor cs = c.getConstructor(String.class, int.class);

        // Create an instance of Person with a parametric construction method
        Person p = (Person) cs.newInstance("Zhang San", 20);
        System.out.println(p.toString());
    }
}

The results are as follows:

/opt/java/jdk-16.0.2/bin/java -javaagent:/opt/idea-IC-212.5457.46/lib/idea_rt.jar=35505:/opt/idea-IC-212.5457.46/bin -Dfile.encoding=UTF-8 -classpath /home/koping/wxp/learn/java/java-web/day20211017/out/production/testReflection com.seleflearn.test2
 Zhang San's age is: 20

Process finished with exit code 0

4. Attributes of Operations Class Using Reflection

1) Get all the properties of the class by getDeclaredFields() method
c.getDeclaredFields();
2) Get the properties of the class by the getDeclaredField() method whose parameter is the name of the property
Field fieldName = c.getDeclaredField("name");
Field fieldAge = c.getDeclaredField("age");
3) When the operation is a private property, the operation privilege needs to be set to true before it can be used
fieldName.setAccessible(true);
fieldAge.setAccessible(true);
4) Set properties for the created instance with two parameters: the first parameter is the instance of the class, and the second parameter is the value to be set
fieldName.set(p, "Zhang San");
fieldAge.set(p, 20);

An example code for setting an instance using the properties of a class is as follows:

package com.seleflearn;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class test3 {
    public static void main(String[] args) throws Exception{
        //Get Class
        Class c = Class.forName("com.seleflearn.Person");

        // Create an instance of Person using a parameterless construction method
        Person p = (Person) c.newInstance();

        // Get the name and age attributes
        Field fieldName = c.getDeclaredField("name");
        Field fieldAge = c.getDeclaredField("age");
        // When operating on a private property, you need to set the operational privilege to true to use it
        fieldName.setAccessible(true);
        fieldAge.setAccessible(true);

        // There are two parameters for setting properties on an instance created: the first parameter is an instance of a class, and the second parameter is the value you want to set
        fieldName.set(p, "Zhang San");
        fieldAge.set(p, 20);

        System.out.println(p.toString());
    }
}

The results are as follows:

/opt/java/jdk-16.0.2/bin/java -javaagent:/opt/idea-IC-212.5457.46/lib/idea_rt.jar=46023:/opt/idea-IC-212.5457.46/bin -Dfile.encoding=UTF-8 -classpath /home/koping/wxp/learn/java/java-web/day20211017/out/production/testReflection com.seleflearn.test3
 Zhang San's age is: 20

Process finished with exit code 0

5. General methods of using reflection operation classes

1) Get all the common methods by getDeclaredMethods()
c.getDeclaredMethods()
2) Get the specified general method by getDeclaredMethod(), and get the specified general method by passing two parameters: the first parameter is the method name, and the second parameter is the parameter type
Method setName = c.getDeclaredMethod("setName", String.class);
Method setAge = c.getDeclaredMethod("setAge", int.class);
3) Once the general method is obtained, invoke is used to make the call, which requires two parameters to be passed: the first parameter is an instance of the class, and the second parameter is the required parameter value for the method.
setName.invoke(p, "Zhang San");
setAge.invoke(p, 20);
4) If the operation is a private method, the operation privilege needs to be set to true first
setName.setAccessible(true);
setAge.setAccessible(true);
5) When the method of operation is a static method, because the static method is called by: class name. static method name
No instance of the class is required, so set the first parameter of the invoke method to null
setName.invoke(null, "Zhang San");
setAge.invoke(null, 20);

An example code for setting up an instance using the general method of a class is as follows:

package com.seleflearn;

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

public class test4 {
    public static void main(String[] args) throws Exception {
        //Get Class
        Class c = Class.forName("com.seleflearn.Person");

        // Create an instance of Person using a parameterless construction method
        Person p = (Person) c.newInstance();

        // To get a general method, two parameters are passed: the first parameter is the method name, and the second parameter is the parameter type.
        Method setName = c.getDeclaredMethod("setName", String.class);
        Method setAge = c.getDeclaredMethod("setAge", int.class);

        // Once the general method is obtained, invoke is used to make the call, which requires two parameters to be passed: the first parameter is an instance of the class, and the second parameter is the required parameter value for the method.
        setName.invoke(p, "Zhang San");
        setAge.invoke(p, 20);
        // Note: If the operation is a private method, the operation privilege needs to be set to true first
        // setName.setAccessible(true);
        // setAge.setAccessible(true);

        System.out.println(p.toString());
    }
}

The results are as follows:

/opt/java/jdk-16.0.2/bin/java -javaagent:/opt/idea-IC-212.5457.46/lib/idea_rt.jar=39419:/opt/idea-IC-212.5457.46/bin -Dfile.encoding=UTF-8 -classpath /home/koping/wxp/learn/java/java-web/day20211017/out/production/testReflection com.seleflearn.test4
 Zhang San's age is: 20

Process finished with exit code 0

Topics: Java Back-end