Reflection --- the soul of frame design

1, What is reflection?

① Frame: it is a semi-finished product! Benefits: improve our development efficiency and make our code more concise

② Reflection: when allowed, the process of extracting members from a class into other classes is called reflection

II. Method of obtaining reflection Class

① Obtained by the full path string of the class

Class.forName("full path")

Example: spring Framework < bean id = "" Class = "full path of Class" > --- you can get Class objects -- Class -------------------- Class objects

② Get by class name

Class name class

Example: mybatis framework: session getMapper(StudentDao.class);----- Reflection class object gets the corresponding class object

③ Get through object class

Object name getClass();

When you know the object of this class, you can obtain the reflection class through the object

public class demo01 {
    public static void main(String[] args)throws Exception {
         //How to get Class
         //(1) Obtained through the full class name string of the class.
        Class aClass = Class.forName("com.ykq.Student");
        //(2) Get by class name
        Class bClass = Student.class;
        //(3) Object
        Student s=new Student();
        Class cClass = s.getClass();
        //Think: are the addresses of Class objects obtained in the above methods the same?
        System.out.println(aClass==bClass); //==Compare reference addresses.
        System.out.println(aClass==cClass);
        System.out.println(bClass==cClass); //There is only one reflective class object for any class.
    }
}
class Student{
     private String name;
     private int age;
     public void show(){
         System.out.println("~~~~~~~show~~~~~~~~~~~");
     }

    public Student() {
    }
}

3, Get the corresponding class object through the reflection class

public   static  void  main(String[]  args)throws  Exception{

        Class<Student> aClass=Student. class;// Get the reflection class object of student

        Student student=aClass.newInstance();// Get the corresponding class object through the reflection class

        System.out.println(student);

}

4, How to get the Field class

Getdeclaraedfield (string name): get the Field object with the specified attribute name in this class

Getdeclaraedfields(): get all attribute objects in this class

getField(String name): gets the Field object (including the attribute of the parent class) of the specified public modified attribute name

getFields(): get all public decorated property objects (including the properties of the parent class)

    public static void main(String[] args) throws Exception {
        System.out.println("===============Get specified public Decorated property object===========");
        Class<?> aClass = Class.forName("com.ykq.demo3.Student");
        Field nameField = aClass.getField("name"); //Gets the name attribute object specified by public
        System.out.println(nameField);
        Field sexField = aClass.getField("sex");
        System.out.println(sexField);
        System.out.println("==================Gets the property object specified in this class=========================");
        Field nameField2 = aClass.getDeclaredField("name");//Gets the property object in this class
        System.out.println(nameField2);
        Field ageField2 = aClass.getDeclaredField("age");//Gets the property object in this class
        System.out.println(ageField2);
//        Field sexField2 = aClass.getDeclaredField("sex");// Gets the property object in this class
//        System.out.println(sexField2);

        System.out.println("===============Get all public Decorated property object=================");
        Field[] fields = aClass.getFields();
        for (Field f:fields) {
            System.out.println(f);
        }

        System.out.println("============Get all property objects in this class===================");
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field:declaredFields) {
            System.out.println(field);
        }

    }

V. what are some operations in the Field class?   

get(Object obj) returns the value Field of the represented Field On the specified object

get(Object obj,Object value) assigns a value to the specified attribute

setAccessible(boolean) sets the visibility of the property

public class Test04 {
    public static void main(String[] args)throws Exception {
        Class<?> aClass = Class.forName("com.zd.demo4.Student");
        Object o = aClass.newInstance();
        Field nameField = aClass.getField("name");
        System.out.println(nameField.get(o));//Gets the value of the property name
        nameField.set(o,"Zhang San");  //Assign a value to the name attribute object
        System.out.println(nameField.get(o));

        Field ageField = aClass.getDeclaredField("age");
        ageField.setAccessible(true);//Set the visibility of private attributes to break the encapsulation of object-oriented
        ageField.set(o,15);//Because private cannot be accessed

        System.out.println(o);
    }
}
class Father{
    public String sex;
}
class Student extends Father {
    public String name;
    private int age;
    public void show(){
        System.out.println("~~~~~~~show~~~~~~~~~~~");
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Student() {
    }
}

6, Get Method of Method class Method:

Getdeclaraedmethod (string name, class <? >... Paramentertypes): get the method object of the specified method name in this class

Getdeclaraedmethods(): get all the methods in this class

Getmethod (string name, class <? >.. paramtertypes): gets the public modified method in the specified class, including the parent class

getMethods(): get all public methods

public class Test05{
    public static void main(String[] args)throws Exception {
        Class<Student> aClass = Student.class;
        Student student = aClass.newInstance();

        Method show = aClass.getMethod("show");
        System.out.println(show);

        Method print = aClass.getMethod("print",Integer.class,String.class);
        System.out.println(print);

        Method fun = aClass.getDeclaredMethod("fun");
        System.out.println(fun);

        //Callback this method --- execute this method.
        show.invoke(student);//Object obj object name Args: parameter value

        fun.setAccessible(true);//Visibility needs to be set when calling private methods
        fun.invoke(student);

        Object o = print.invoke(student, 25, "China");

        Method toString = aClass.getMethod("toString");
        Object invoke = toString.invoke(student);
        System.out.println(invoke);
    }
}

class Father{
    public String sex;
    public void print(Integer age,String address){
        System.out.println("In parent class print method"+age+";address:"+address);
    }
}//

class Student extends Father {
    public String name;
    private int age;
    public void show(){
        System.out.println("~~~~~~~show~~~~~~~~~~~");
    }
    private void fun(){
        System.out.println("~~~~~~~fun~~~~~~~~~~~");
    }
    @Override
    public String toString() {
        return "Student{" +
                "sex="+sex+
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Student() {
    }
}

7, Get how to construct class Constructor:

getConstructor (class <? >... Parametertypes)

getConstructors()

This class has methods in the Constructor: if there is no parameterless Constructor in the class

newInstance

public class Test06 {
    public static void main(String[] args)throws Exception {
        Class<Teacher> aClass = Teacher.class; //Only parameterless constructors can be called
//        Constructor<Teacher> constructor = aClass. getConstructor();// Parameterless constructor object
//        Teacher teacher = constructor.newInstance();
//        System.out.println(teacher);

        Constructor<Teacher> constructor2 = aClass.getConstructor(int.class);//Gets a one parameter constructor object whose parameter type is String
        Teacher teacher = constructor2.newInstance(15);
        System.out.println(teacher);

        Constructor<Teacher> constructor = aClass.getConstructor(String.class, int.class);
        Teacher t = constructor.newInstance("Li Si", 18);
        System.out.println(t);
    }
}
class Teacher{
    private String name;
    private int age;

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Teacher() {
        System.out.println("No parameter");
    }

    public Teacher(String name) {
        System.out.println("meal");
        this.name = name;
    }
    public Teacher(int age) {
        System.out.println("meal");
        this.age = age;
    }

    public Teacher(String name, int age) {
        System.out.println("Total disability");
        this.name = name;
        this.age = age;
    }
}

8, Get Annotation class object Annotation

You can get the annotation object on the class, the annotation object on the attribute and the annotation object on the method

public class Test07 {
    public static void main(String[] args)throws Exception {
        System.out.println("Gets the annotation object on the class");
        Class<Doctor> aClass = Doctor.class;
        Service annotation = aClass.getAnnotation(Service.class);
        System.out.println(annotation);
        System.out.println(annotation.value());

        System.out.println("Gets the annotation object on the property");
        Field nameField = aClass.getDeclaredField("name");
        JsonProperty annotation1 = nameField.getAnnotation(JsonProperty.class);
        System.out.println(annotation1.value());
        System.out.println(annotation1.required());

        System.out.println("Gets the annotation object on the method");
        Method hello = aClass.getMethod("hello");
        RequestMapping annotation2 = hello.getAnnotation(RequestMapping.class);
        System.out.println(Arrays.toString(annotation2.value()));
    }
}
@Service(value = "hello")
class Doctor{
    @JsonProperty(value = "n",required = true)//Value required is the attribute of the annotation
    private String name;
    @RequestMapping(value = {"hello2","hahaha","hehe"})
    public void hello(){
        System.out.println("hello");
    }
}

Keywords: Java WPF linq

Added by stiduck on Sat, 25 Dec 2021 21:44:44 +0200