What is the function of reflection and what can it do for us?

What can reflection do

  • For any class, you can know all the properties and methods of this class;
  • For any object, you can call any of its methods and properties.

Reflection common classes

Constructor class: provides information about the construction method of the class and its access rights. Field class: provides information about the field on the class or interface and its dynamic access rights. Method class: provides information about a method on a class or interface.

Class class

In the object-oriented world, everything is an object. Class is also an object, which is Java An example object of the lang. class class. Class class has no public constructor. How to create class objects?

Three methods of creating Class objects

  • Use the class attribute of the class
Class c = Demo.class
  • Use the forName method of Class
try {
    Class c = Class.forName("xin.zhuyao.gzh.test20200722.Demo");
    //When creating a Class object using the forName method of Class, you need to catch ClassNotFoundException
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}
  • Use the getClass method of the Object object
Demo demo = new Demo();
Class c = demo.getClass();

Although there are three methods, the reflection objects they create are exactly the same, that is, a class can only have one reflection object, and interested partners can test it.

Main methods of Class

Construction method

//Obtain all constructor methods with public permission
Constructor<?>[] getConstructors();

//Gets the specified constructor with permission public
Constructor<T> getConstructor(Class<?>... parameterTypes);

//Get all construction methods and return them in the declared order
Constructor<?>[] getDeclaredConstructors();

//Gets the specified construction method
Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes);

method

//Get all methods with public permission
Method[] getMethods();

//Obtain the specified method with public permission
Method getMethod(String name, Class<?>... parameterTypes);

//Get all the methods and return them in the declared order
Method[] getDeclaredMethods();

//Gets the specified method
Method getDeclaredMethod(String name, Class<?>... parameterTypes);

Member variable

//Get a member variable with public permission
Field[] getFields();

//Gets the specified member with public permission
Field getField(String name);

//Get all member variables and return them in declaration order
Field[] getDeclaredFields();

//Gets the specified member variable
Field getDeclaredField(String name);

Note: when obtaining member variables and methods with public permission through getFields() and getMethods(), the member variables and methods inherited from the superclass will be included; Only all member variables and methods defined in this class can be obtained through the methods getdeclaraedfields() and getdeclaraedmethods().

The acquisition construction method and acquisition method are not introduced here. If you are interested, you can check it yourself. Here we only introduce the class of obtaining member variables, that is, Field

Main methods of Field class

method

//Gets the name of the member variable
String getName();

//Gets the Class object represented to the member variable type
Class<?> getType();

//Gets the value of the member variable in the specified Object and returns Object type
Object get(Object obj);

//Sets the value of the member variable in the specified object to obj
void set(Object obj, Object value);

//Gets the member variable of type int in the specified object
int getInt(Object obj);

//Set the value of the member variable of type int of the specified object to i
void setInt(Object obj, int i)

//. . .  If there are all eight data types, they will not be listed one by one

//This method can set whether to ignore permission restrictions and directly access member variables with private permissions such as private
void setAccessible(boolean flag);

After writing so much, when can we use it? Now, for example, there are two classes, such as Fang DO (database class) and DTO (special class for data processing). Many fields between them are the same. Now I want to transfer the data in DO to DTO for data processing. DO we want to get and set one by one? We can write a tool class.

purpose

DemoDO

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DemoDO {

    private Integer id;

    private String name;

    private Integer sex;
    
    private String password;
}

DemoDTO

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DemoDO {

    private Integer id;

    private String name;

    private Integer sex;
    
}

Tool method

public static <S,T> T copyProperties(S source, Class<T> tClass){
    try {
        Class<?> sClass = source.getClass();
        T target = tClass.newInstance();
        if (null == source){
            return target;
        }
        Field[] fields = tClass.getDeclaredFields();
        for (Field field : fields) {
            try {
                Field declaredField = sClass.getDeclaredField(field.getName());
                field.setAccessible(true);
                declaredField.setAccessible(true);
                field.set(target,declaredField.get(source));
            } catch (NoSuchFieldException e) {
                log.info("There is no such field:{}",field.getName());
            }
        }
        return target;
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(String.format("%s must declaring none arguments constructor!", tClass.getTypeName()));
    }
}

test

public static void main(String[] args) {
    DemoDO demoDO = DemoDO.builder().id(1).name("zy").sex(1).password("123").build();
    DemoDTO demoDTO = copyProperties(demoDO, DemoDTO.class);
    System.out.println(demoDTO.toString());
}

result

DemoDTO(id=1, name=zy, sex=1)

Of course, this is just an example. In fact, spring has already provided tools in this regard, BeanUtils Small partners interested in copyproperties can learn about it.

Added by transformationstarts on Thu, 20 Jan 2022 18:26:03 +0200