Reflection of java Foundation

catalogue

1: Concept

2: Get class file object

3: Gets the constructor in the class file

4: Get member variables through reflection and use

5: Get member methods through reflection and use

6: Explain

1: The class used is the student class (below)

2: About throwing anomaly

1: Concept

Java reflection mechanism is to know all the properties and methods of any class in the running state; For any object, you can call any of its methods and properties; This kind of dynamically acquired information and the function of dynamically calling object methods are called the reflection mechanism of Java language.

In fact, it is to use the member variables, construction methods and member methods in the class file object

2: Get class file object

1: Get through the getClass() method in the Object and return the runtime class of the Object

2: Get static attribute class by class name

3: Static methods in Class (the most commonly used method in development)

public static class <? > Forname (string classname) / returns the class object associated with the class or interface with the given string name// Note: this class needs to be written here, and the middle of the complete path in this project is connected by points

package day34;

public class Test1 {
    public static void main(String[] args) {
       Student student = new Student();
       //Get class object through getClass
       Class<? extends Student> aClass = student.getClass();
        System.out.println(aClass);
        //Get class object through. Class
        Class<Student> studentClass = Student.class;
        System.out.println(studentClass);
        try {
            //Get through Class.forName
            Class<?> aClass1 = Class.forName("day34.Student");
            System.out.println(aClass1);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }
}

  3: Gets the constructor in the class file

1: public Constructor<?> [] getconstructors() / / returns an array containing the constructor object, / / reflecting all public class functions of the class represented by the constructor object. Including obtaining private and default decoration construction methods

2: public Constructor<?> [] getdeclaredconstructors() / / returns the array class of all constructor objects that reflect the class declaration represented by the constructor object// Get all construction methods, including private methods. This method breaks the barrier that the original private construction methods cannot create objects

3: Gets the construction method of a single

Public Constructor < T > getconstructor (class <? >... Parametertypes) / / returns a Constructor object that reflects the specified public class function of the class represented by the Constructor object.

Public Constructor < T > getdeclaraedconstructor (class <? >... Parametertypes) / / returns a Constructor object that reflects the specified class function of the class or interface represented by the Constructor object

Note that if there are parameters, you need to get the class object of the parameters

4: Create objects according to the construction method

public T newInstance(Object... initargs) / / the constructor represented by the object. Use the specified initialization parameters to create and initialize a new instance of the constructor's declaration class.

package day34;

import java.lang.reflect.Constructor;

public class Test2 {
    public static void main(String[] args) {
        //Gets the class object of the Student
        Class<Student> stu = Student.class;
        //Get public constructor and output
        Constructor<?>[] constructors = stu.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println("==================================");
        //Get all construction methods and output
        Constructor<?>[] declaredConstructors = stu.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }
        System.out.println("==================================");
        try {
            //Get public parameterless construct
            Constructor<Student> constructor = stu.getConstructor();
            System.out.println(constructor);
            System.out.println("===============================");
            //Get private parameterized constructs
            Constructor<Student> declaredConstructor = stu.getDeclaredConstructor(String.class);
            System.out.println(declaredConstructor);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

  4: Get member variables through reflection and use

1: public Field[] getFields() gets all member variables. / / a Field object containing an array is returned, reflecting all accessible public Field class objects of the class or interface represented by it// Gets all public member variables in the class

2: public Field[] getDeclaredFields() / / the returned array Field object reflects all Field class objects declared by the class or interface represented by this / / get all member variables, including public, protected, default (package) access and private fields

4: Get a single member variable

public Field getField(String name) gets the public member variable

public Field   Getdeclaraedfield (string name) gets the public member variable

void set(Object obj, Object value)

//Sets the Field represented by this Field object on the specified object parameter to the specified new value.

If you don't have access, you can use   setAccessible(true) for brute force access

package day34;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class Test3 {
    public static void main(String[] args) throws Exception{
        Class<?> stu = Class.forName("day34.Student");//Get student class object
        Constructor<?> constructor = stu.getConstructor();//Get parameterless public construct
        Object o = constructor.newInstance();//Creating student objects from nonparametric constructs
        System.out.println(o);//Output object
        System.out.println("==========================");
        //Get public variables and output
        Field[] fields = stu.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("==========================");
        //Get all variables and output
        Field[] declaredFields = stu.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
        System.out.println("==========================");
        //Get a single variable and assign it, and then output the assigned object again
        Field sex = stu.getField("sex");
        sex.set(o, "male");
        Field name = stu.getDeclaredField("name");
        //Violent access. IllegalAccessException when there is no permission assignment
        name.setAccessible(true);
        name.set(o, "floret");
        System.out.println(name);
        Field age = stu.getDeclaredField("age");
        //Violent access. IllegalAccessException when there is no permission assignment
        age.setAccessible(true);
        age.set(o, 18);
        System.out.println(o);

    }
}

  5: Get member methods through reflection and use

1: Public method [] getMethods() / / returns all public method class objects containing an array method object that reflects the class or interface represented thereby, / / including those declarations inherited from the class or interface and those inherited from the superclass and superinterface// All public methods are obtained, not only their own public methods, but also those of the parent class

2: Public method [] getDeclaredMethods() / / returns all declared methods of the class or interface reflected by an array method object, which represents the class object. / / including public, protected, default (package) access and private methods, but excluding inherited methods// You can only get all your own methods, including private ones

3: Public method getMethod(String name, class <? >... Parametertypes) / / returns a method object that reflects the specified public member method class object of the represented class or interface// Note: write only the method name, not the parentheses  

4: The public method getdeclaraedmethod (string name, class <? >... Parametertypes) returns a method object, including public, protected, default (package) access and private methods

5: Object invoke(Object obj, Object... args) / / call the underlying method represented by this method object on the method object with the specified parameters.

package day34;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class Test4 {
    public static void main(String[] args) throws Exception{
        Class<?> aClass = Class.forName("day34.Student");//Create student class object
        //Get all public methods and public methods of the parent class and output them
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("=============================");
        //Get all methods, including private methods, and output
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }
        System.out.println("=============================");
        //Get the student's nonparametric construct, and then create an object based on the nonparametric construct
        Constructor<?> constructor = aClass.getConstructor();
        Object o = constructor.newInstance();
        //Get a single method and execute it
        Method show = aClass.getMethod("show");
        show.invoke(o);
        Method show1 = aClass.getDeclaredMethod("show", int.class);
        show1.setAccessible(true);//Violent visit
        Object invoke = show1.invoke(o,10);
        Method study = aClass.getDeclaredMethod("study");
        study.setAccessible(true);//Violent visit
        study.invoke(o);
    }
}

6: Explain

1: The class used is the student class (below)

package day34;

public class Student {
    private int age;


    public String sex;
    private String name;

    public Student() {
    }
    private Student(String sex){
        this.sex=sex;

    }

    public Student(int age, String sex) {
        this.age = age;
        this.sex = sex;
    }
    public void show(){
        System.out.println("show");
    }
    private void show(int i){
        System.out.println("show"+"**"+i);
    }
    private void study(){
        System.out.println("study");
    }
    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", sex='" + sex + '\'' +
                ", name='" + name + '\'' +
                '}';
    }


}

2: About throwing anomaly

Because there will be errors, if the project is normally done, it should be try...catch, but for the purpose of method viewing, a large exception is thrown directly on the main method

Keywords: Java Back-end

Added by the elegant on Thu, 11 Nov 2021 10:58:03 +0200