The previous article introduced the basic concepts of reflection and the reflection API for obtaining information about a class. This section focuses on the reflection API for how to operate on the members of a class.

Classes that operate on class members

The reflection API provides the following interface for manipulating members of a class.

 java.lang.reflect.Member
Copy the code

The interface has three main implementation classes that operate on fields, methods, and constructors in class members.

Tips: As stated in the Java SE 7 manual, constructors are not members of classes, which is not what the Member implementation class means.

The operating field

A field has a type and a value. Use the following classes to get the type information of the field in the class, get the value of the field, and assign the value to the field.

 java.lang.reflect.Field
Copy the code

Operation method

Methods have return values, parameters, and may throw exceptions. Use the following classes to get the parameters of a method and the type of the return value, or to call a method on a given object.

 java.lang.reflect.Method
Copy the code

Operation constructor

The following classes operate on the constructor of a class, providing methods similar to methods, except that the constructor does not return a value, and calls to the constructor create instances of the specified class.

 java.lang.reflect.Constructor
Copy the code

The actual operation

Get field type

public class Main {

	public static String abc = "123";
	private static List<String> a;

	public static void main(String[] args) throws NoSuchFieldException {
		Class c = Main.class;
		Field field = c.getField("abc");
		Field field1 = c.getDeclaredField("a"); System.out.println(field.getType()); System.out.println(field.getGenericType()); System.out.println(); System.out.println(field1.getType()); System.out.println(field1.getGenericType()); }}Copy the code

As shown in the code above, get the Field class of the corresponding Field. The specific use difference is described at the end of the previous article. GetType directly prints the class type of this field. GetGenericType directly prints the type of the field, or if it is a generic field, the type with the actual parameter of the generic, or if it is not generic, getType is called internally. The results are shown below.

class java.lang.String
class java.lang.String

interface java.util.List
java.util.List<java.lang.String>
Copy the code

Gets the field modifier

Class modifiers public, private, transient, etc. Java provides API access to class modifiers, but obtain an int number, good Java provides Modifier to determine the obtained integer, as shown in the following code: Interested can browse the Modifier source code.

public class Main {
    public static int a = 1;
    public static void main(String[] args) throws NoSuchFieldException {
        Class c = Main.class;
        Field field = c.getField("a"); System.out.println(Modifier.isPublic(field.getModifiers())); System.out.println(Modifier.isStatic(field.getModifiers())); }}Copy the code

Read and write field values

Reflection can read and write fields, as shown in the following code. You can use setX and getX methods to read and write fields, but pay attention to whether the types before and after reading and writing fields match, otherwise an exception will be reported.

    private static int a = 1;

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Class c = Main.class;
        Field field = c.getDeclaredField("a");
        int b = field.getInt(Main.class);
        System.out.println(b);
        field.setInt(Main.class, 2);
        System.out.println(a);
        field.setFloat(Main.class, (float) 1.1);   / / the anomalies
    }
Copy the code

Operation methods and constructors

The following classes operate on methods (Method) and constructors (Constructor). You can get information about methods and constructors through the GET methods provided by these apis, so I won’t go into this in my notes.

The constructor creates the instance

The reflection class difference between constructors and methods is that Constructor can create instances, as shown below.

public class Main {

    public Main(a) {}public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        Class c = Main.class;
        Constructor[] ctors = c.getConstructors();
        Constructor ctor = null;
        for (int i = 0; i < ctors.length; i++) {
            ctor = ctors[i];
            if (ctor.getGenericParameterTypes().length == 0)     // You need to find the default constructor to create the instance
                break; } System.out.println(ctor.newInstance().getClass().getCanonicalName()); }}Copy the code

At the end

The above is some records of reflection API. This tool itself is very simple to use, but its significance is still relatively large, which is the foundation of many frameworks. The next article takes Struts as an example to write a small demo to show the application of reflection in it.