Hello everyone, I am Wolf King, a programmer who loves playing ball

This article lets us talk about what is reflection, why many programmers hear reflection inexplicably afraid of it, this article to you emboldened, in fact, there is no much thing!


In Java, the most effective means of manipulating methods and properties of objects at runtime is reflection. This is also the most common approach used by frameworks, because the framework does not know at compile time what classes will be used in the system.

The type information of objects in Java is represented at run time by Class objects, which are instantiated with Class loading, and reflection is implemented around Class objects.

There are several ways to get the Class object of a Class, including:

Class<Object> c1 = Object.class; Class<? > c2 = Class.forName("java.lang.Object"); Class<? > c3 =new Object().getClass();
Copy the code

What can reflection do?

1. Instantiate the object

Object instantiation, either directly via the new keyword or via reflection, for example:

class.newInstance() class.getConstructor(Class<? >... parameterTypes).newInstance(Object ... initargs)Copy the code

Why do we need reflection to instantiate objects?

  1. There are scenarios where objects cannot be directly instantiated using the new keyword, such as Spring container-managed beans, which can only be loaded by the class’s fully qualified name and then instantiated by reflection.
  2. In scenarios where you don’t want to use the new keyword, the purpose is to simplify programming and make the code beautiful. You may often see similar uses, such as:

public static <T> T parseObject(String text, Class<T> clazz) {
  return parseObject(text, clazz, new Feature[0]);
}
Copy the code
/** * simply copy the new type object */
public static <S, D> D map(S source, Class<D> destinationClass){
  return mapper.map(source, destinationClass);
}
Copy the code

2. Filter the right classes

In real development, there is often a need to do something if the class has something. When Spring scans, we use filters to refine the generation of control beans, including:

  1. According to isInstance(Object obj) to determine whether to implement a certain interface or inherit a special parent class;
  2. According to the isAnnotationPresent (Class
    annotationClass) determines whether it is annotated.

3. Method calls

There are situations in which calling a method directly cannot or is not appropriate. For example, when we are processing HTTP requests and need to map from URIs to method calls, it would be fine if we could enumerate all the MAPPINGS between URLs and object methods, but countless if criteria are obviously not a wise choice.

We usually get the resource object first and then reflect the method that calls the object.

Method.invoke(Object obj, Object... args)
Copy the code

How do you get the Method object of an object, the Method object? The Class Class provides the following implementation:

Method[] getMethods(); Method[] getDeclaredMethods(); Method getMethod(String name, Class<? >... parameterTypes); Method getDeclaredMethod(String name, Class<? >... parameterTypes);Copy the code

These methods fall into two categories:

  1. Method signatures with Declared will be looked up in all methods of the current class, but will not traverse the parent class.
  2. Classes without Declared will traverse all parent classes, but will only look for public methods.

Recommended tools: org.apache.com mons. Lang3. Reflect the MethodUtils such traverse all contained in the parent class method, the current class search public methods or reflection execution method and convenient operation.

4. Attribute operations

Class.getFields(), Class.getField(String), 
Class.getDeclaredFields(), Class.getDeclaredField(String)
Copy the code

Naming rules and methods, it is recommended to use tools: org.apache.com mons. Lang3. FieldUtils, read or assignment operation.

There are a few things to note about reflection assignment:

  1. If the Field is not of type public, the access permission must be set using the field.setaccessible (true) method before setting the Field. Otherwise, an IllegalAccessException will be thrown.
  2. If the field is static, assignment through the set method ignores the obj object because static fields are classes.
  3. If a field is final, whether public or private, then the set assignment must be set with setAccessible. Otherwise, IllegalAccessException is reported. However, when the set method is assigned to a final field, it does not change the value of the FIanl field, even though the method is called normally.
  4. If the field is of final static type, an IllegalAccessException will always be thrown when the set method is assigned.

Finally, if all the way to the current object, some or all of the fields for operation, the recommended tools: org. Springframework. Util. ReflectionUtils

4, summarize

So reflexes are not that scary, the best way to eliminate fear is to face it, come on!

All right. Today’s cattle blowing here, I will share their own learning and thinking, I hope we walk together on the road to success!

Willing to output dry Java technology public number: Wolf king programming. The public number has a large number of technical articles, massive video resources, beautiful brain map, might as well pay attention to it! Get lots of learning resources and free books!

Forwarding moments is the biggest support for me!

\

Click “like and watching” if you feel something! Thank you for your support!

\