That's what the framework principle is about -- reflection.

Keywords: Java JSON

I remember writing an article about json's transformation of entities before.
<!-- more -->

I remember that I wrote an article about json's transformation of entity, in which I used java reflection. But I only learned about reflection at that time, but I didn't have a thorough understanding of it. During the winter vacation, I did a thorough collation of java reflection knowledge, which is the summary of my personal learning reflection. What I can't do is hopeful. Divine Direction!!!

Reflection, as the name implies, is the opposite of java compilation. The effect here is to instantiate class objects and manipulate classes through class names. Look at it concretely

Get the parent class and all the interfaces

  • First of all, our java class can inherit and implement multiple interfaces, so how can we get the parent class and interface of java class through java reflection?
  • First, we'll create a new Annimal here as the parent class.
public class Annimal {

    private String AnnimalName;
    
    public void eat(){
        System.out.println("Annimal is eatting");
    }
    public void run(){
        System.out.println("Annimal is running");
    }
}
  • Then create a new Behaviour interface
public interface Behaviour {

    public String haviour="test";
    
    public void sayHello();
    
    public void isAngury();
    
    public void love();
}
  • Now let's create a new Dog class and let the Dog class inherit the Annimal class and implement the Behavour interface.
public class Dog extends Annimal implements Behaviour
  • Dog source code
public class Dog extends Annimal implements Behaviour{

    private String dogName;
    
    public void fuck(String name){
        System.out.println("fuck To : "+name);
    }
    @Override
    public void sayHello() {
        // TODO Auto-generated method stub
        System.out.println("Dog sayHello");
    }

    @Override
    public void isAngury() {
        // TODO Auto-generated method stub
        System.out.println("Dog isAngury");
    }

    @Override
    public void love() {
        // TODO Auto-generated method stub
        System.out.println("Dog love");
    }

}
  • test
  • Now let's start testing. First, we get the class object of the class through the Class class.
Class<?> target=Class.forName("tom.change.Reflect.Get the parent class and all interfaces.Dog");

  • Then the parent class and all interfaces can be obtained by getSuperClass and getInterfaces.
//Get the parent class of the Dog class
Class<?> parent=target.getSuperclass();
//Get all classes inherited by this class
Class<?> intefaces[]=target.getInterfaces();
  • Finally, look at the results of the program running

Get all attributes (getDeclared Fields)

  • In Java classes, there are relations between classes and classes, and each class has specific properties. So how can we get the properties in Java classes by reflection? Next I write a user class with attributes of

Dog class:

    private String dogName;
  • So let's try to get the above attributes. Similarly, class objects are retrieved through class paths
Class<?> clazz=Class.forName("tom.change.Reflect.Get the parent class and all interfaces.Dog");
  • Then get the attributes of the local class through the getDeclared Fields method of the class object. This method can't get the attributes in the inherited parent class and interface. If you want to get the attributes, you can get the attributes in the parent class first, then get the class object of the parent class, and then get the attributes in the parent class.
for (int i = 0; i < fields.length; i++) {
            //Gets the modifier permission character for the field
            System.out.println(Modifier.toString(fields[i].getModifiers())+"@@@"+fields[i].getName());
        }
  • Let's say that after acquisition, the class getModifiers is accepted by Field, whether it is private, public or protected.
  • Once you get the fields here, you can set the properties through Field's set method, regardless of the external state of the properties. The premise is to open permission
field.setAccessible(true);
field.set(object, "21131084");
  • Here object is an instantiated object of class

Get all the methods in the class

  • We've got all the attributes in the class above, so naturally we'll get all the methods in the class below. The same steps are already in place, not to mention here, but the difference is that we call the getMethods method after we get the class object.
public void tom.change.Reflect.Get the parent class and all interfaces.Dog.fuck(java.lang.String)
public void tom.change.Reflect.Get the parent class and all interfaces.Dog.sayHello()
public void tom.change.Reflect.Get the parent class and all interfaces.Dog.love()
public void tom.change.Reflect.Get the parent class and all interfaces.Dog.isAngury()
public void tom.change.Reflect.Get the parent class and all interfaces.Annimal.run()
public void tom.change.Reflect.Get the parent class and all interfaces.Annimal.eat()
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
  • Do you have any questions about why some inexplicable methods have appeared, some methods have not even appeared in our Dog and inheritance classes? What's the matter? First, getMethods gets the method of the class itself, which is positive. We can also acquire inherited classes, which explains why we have methods in Annimal classes. So where did the methods of the latter Object classes come from? Do you remember that all the classes inherit Object classes?

Method calls in classes

  • After we get the method above, we get the specified method through getMethod, which returns the Method object, and then invokes the specified method through the invoke method in Method. When calling, we need to pass in the class strength object. If we have parameters, we also need to pass in parameters.
public Object invoke(Object obj, Object... args)
  • The source code shows that the method needs as many parameters as it needs to pass in here, which is universal.
  • We need to pass in the type of Method parameters when we get the Method through getMethod

    public Object invoke(Object obj, Object... args)
    public Method getMethod(String name, Class<?>... parameterTypes)

Get all constructors

  • Finally, there should be a constructor left in the Java class. Since it's reflection, we need to make dry crystals of reflection. After obtaining the class object, we get the constructor through getConstructors, which returns the Constructor set. In the Constructor class, getParameterTypes get the parameters in the constructor. With this, we can construct the class ourselves.

summary

  • At this point, our reflection is fully operational on a class. Some people will ask what this means, in our Java web, which well-known framework source code must have reflection, through which we can achieve annotation function. Of course, annotations have other knowledge, which will be introduced later. For example, when we map a map to an entity, we need the reflector to get the attributes in the Java Bean and assign the values of the map. In any case, reflection is an important knowledge of Java, and learning it will be very helpful for our future architectural trials.

< font face = Italic size = 6 color = Red > Source Download</font>

Join the team

<span id="addMe">Join the team</span>

Wechat Public Number

Posted by snowdog on Tue, 10 Sep 2019 00:17:48 -0700