Task five reflection mechanism

Reflection mechanism

1. Basic concepts

  • Under normal circumstances, writing code is fixed, and the result of execution is fixed no matter how many times it is run. In some special occasions, when writing code, you are not sure what type of object to create or what method to call. These They all hope to be determined by the parameters passed at runtime. This mechanism is called dynamic programming technology, which is the reflection mechanism.
  • Generally speaking, the reflection mechanism is a mechanism used to dynamically create objects and dynamically call methods. At present, the bottom layer of mainstream framework is implemented by reflection mechanism.
  • Such as:
  • Person p = new Person();-indicates that the reference to the Person type points to an object of type Person
  • p.show();-means to call the member method show in the Person class

2.Class class

basic concept

  • Instances of the java.lang.Class class can be used to describe the classes and interfaces in a Java application, that is, a data type.
  • There is no public construction method for this class. The instance of this class is automatically constructed by the Java virtual machine and the class loader. In essence, it is a runtime class loaded into memory.

How to get the Class object

  • Use the data type .class to obtain the Class object of the corresponding type (master).
  • Use reference/object.getClass() to get the Class object of the corresponding type.
  • Use the wrapper class .TYPE way to get the Class object corresponding to the basic data type.
  • Use Class.forName() to obtain the Class object of the type specified by the parameter (master).
  • Use the class loader ClassLoader to obtain the Class object of the specified type.

Commonly used methods (mastery)

  • static Class forName(String className) is used to get the Class object corresponding to the specified type of the parameter and return it
  • T newInstance() is used to create a new instance of the class represented by the Class object
public class ClassTest {
    
    

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

        //1.使用数据类型.class 获取对应类型的class对象
        Class c = String.class;
        System.out.println(c);//class java.lang.String
        c = int.class;
        System.out.println(c);//int
        System.out.println(void.class);//void]
        //2.用对象.getClass()的方式获取对应的class对象
        String str = new String("123456");
        c = str.getClass();
        System.out.println(c);//class java.lang.String
        Integer i = 12;
        System.out.println(i.getClass());//class java.lang.String
        //3.使用包装类.TYPE的方式来获取对应基本数据类型的class类型
        Class<Integer> type = Integer.TYPE;
        System.out.println(type);
        //4.调用class类中forname方法来获取对应的class对象
        //Class<?> string = Class.forName("String");//错误的写法
        Class<?> string = Class.forName("java.lang.String");
        Class<?> string2 = Class.forName("java.util.Date");
        System.out.println(string.toString() + string2);

        //5.使用类加载器ClassLoader获取class对象
        ClassLoader classLoader = ClassTest.class.getClassLoader();
        System.out.println(classLoader);
        Class<?> aClass = classLoader.loadClass("java.lang.String");
        System.out.println(aClass);

    }
}

3.Constructor class

basic concept

  • The java.lang.reflect.Constructor class is mainly used to describe the obtained construction method information

Common methods of Class

  • Constructor getConstructor(Class... parameterTypes) is used to obtain the public construction method specified by the parameters in the type represented by this Class object
  • Constructor[] getConstructors() is used to obtain all public construction methods in the type represented by this Class object

Common methods of Constructor class

  • T newInstance(Object… initargs) Use the construction method described by this Constructor object to construct a new instance of the representative type of the Class object
  • int getModifiers() Get the access modifiers of the method
  • String getName() Get the name of the method
  • Class[] getParameterTypes() Get the types of all parameters of the method
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class PersonConstructorTest {
    
    

    public static void main(String[] args) throws ClassNotFoundException, IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    
    

        //1.使用原始方式以无参方式构造Person类型的对象并打印
        Person p1 = new Person();
        System.out.println("无参方式创建的对象是:" + p1);

        System.out.println("----------------");

        //2.使用反射机制以无参方式构造Person对象
        //创建对象的类型可以从键盘输入
        //System.out.println("请输入要创建的对象类型:");
        //Scanner scanner = new Scanner(System.in);
        //String s = scanner.next();
        //Class c1 = Class.forName(s);
        //创建对象的类型可以从键盘读取
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\lagou\\IO流\\a.txt")));
        String s1 = bufferedReader.readLine();
        Class c1 = Class.forName("com.lagou.teachingCase.task13.Person");
        Class c2 = Class.forName(s1);
        //下列方式已经过时
        //System.out.println("无参方式创建的对象是:" + c2.newInstance());

        //获取Class对象 对应的无参构造方法
        Constructor constructor = c1.getConstructor();
        //使用获取到的无参构造方法来获取无参类型对象,也就是Person类型对象
        System.out.println("使用无参方式构造的对象是:" + constructor.newInstance());

        System.out.println("--------------------------------");
        //3.使用原始有参方式构造Person类型对象
        Person zhangfei = new Person("zhangfei", 33);
        System.out.println(zhangfei);

        System.out.println("-----------------------------------");
        //4.使用反射机制以有参方式构造对象并打印
        //获取class对象中对应的有参构造方法,也就是Person类中的有参构造
        Constructor constructor1 = c1.getConstructor(String.class, int.class);
        //使用获取到的有参构造 构造对象
        //newInstance 中的实参是用于给构造方法中的形式参数传递参数的,也就是name和age进行初始化
        System.out.println("有参构造方式构造的对象:" + constructor1.newInstance("zhangei",30));

        System.out.println("----------------------------------------");
        //5.使用反射机制获取Person类中所有的公共构造方法并打印
        Constructor[] constructors = c1.getConstructors();
        for(Constructor c: constructors){
    
    
            System.out.println("构造方法的访问修饰:" + c.getModifiers());
            System.out.println("构造方法的方法名称:" + c.getName());
            Class[] parameterTypes = c.getParameterTypes();
            System.out.print("构造方法的参数类型:");
            for (Class cc: parameterTypes){
    
    
                System.out.print(" " + cc);
            }
            System.out.println();

        }
    }
}

4.Field class

basic concept

  • The java.lang.reflect.Field class is mainly used to describe the obtained information of a single member variable.

Common methods of Class

  • Method declaration function introduction Field getDeclaredField(String name) is used to obtain the information of a single member variable specified by the parameter in the class represented by this Class object
  • Field[] getDeclaredFields() is used to obtain all member variable information in the class represented by this Class object

Common methods of the Field class

  • Object get(Object obj) Get the value of the member variable represented by this Field object in the parameter object obj
  • void set(Object obj, Object value) Modify the value of the member variable represented by this Field object in the parameter object obj to the value of the parameter value
  • void setAccessible(boolean flag) When the actual parameter is passed true, the reflection object should cancel the Java language access check int
  • getModifiers() Get access modifiers of member variables
  • Class getType() Get the data type of the member variable
  • String getName() Get the name of the member variable
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class PersonFieldTest {
    
    

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

        //1.使用原始方式构造
        Person p1 = new Person("zhang", 22);
        System.out.println(p1.getName());
        System.out.println("---------------------------");
        //2.使用反射机制
        Class<?> aClass = Class.forName("com.lagou.teachingCase.task13.Person");

        Constructor<?> constructor = aClass.getConstructor(String.class,int.class);

        Object zhangfei = constructor.newInstance("zhang", 22);

        Field field = aClass.getDeclaredField("name");
        //设置访问权限的取消 暴力反射
        field.setAccessible(true);

        //获取对象zhangfei中名字为field的成员变量的数值
        System.out.println("获取到的成员变量:" + field.get(zhangfei));//zhang

        System.out.println("---------------------------");
        //3.修改成员变量的数值后再打印
        p1.setName("guanyu");
        System.out.println("原始方式 修改后:" + p1.getName());

        System.out.println("---------------------------");
        //4.使用反射机制修改成员变量的数值后打印
        //表示修改对象zhangfei中名字为field的成员变量,也就是name的数值修改为关羽
        field.set(zhangfei,"guanyu");
        System.out.println("获取到的成员变量:" + field.get(zhangfei));//zhang
        System.out.println("---------------------------");

        //5.获取class对象对应类中的所有成员变量getdeclaredfields
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field f : declaredFields){
    
    
            System.out.println("获取到的访问修饰符为: " + f.getModifiers());
            System.out.println("获取到的数据类型为: " + f.getType());
            System.out.println("获取到的成员变量名称为: " + f.getName());
            System.out.println();
        }



    }
}

5.Method class

basic concept

  • The java.lang.reflect.Method class is mainly used to describe the obtained method information of a single member.

Common methods of Class

  • Method getMethod(String name, Class… parameterTypes) is used to obtain the Class object, which means that the name in the class is the name parameter
  • The designated public member method of parameterTypes Method[] getMethods() is used to obtain the Class object representing all public member methods in the class

Common methods of the Method class

  • Object invoke(Object obj, Object... args) Use the object obj to call the member method represented by this Method object, and the actual parameters are passed args
  • int getModifiers() Get the access modifiers of the method
  • Class getReturnType() Get the return value type of the method String getName() Get the name of the method
  • Class[] getParameterTypes() Get the types of all parameters of the method
  • Class[] getExceptionTypes() Get the exception information of the method
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class PersonMethodTest {
    
    

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

        //1.使用原始方式调用方法
        Person zh = new Person("zh", 20);
        System.out.println(zh.getName());

        //2.使用反射机制
        //获取class对象
        Class<?> aClass = Class.forName("com.lagou.teachingCase.task13.Person");
        //根据class对象获取构造
        Constructor<?> constructor = aClass.getConstructor(String.class, int.class);
        //使用有参构造构造对象
        Object o = constructor.newInstance("zhangfei", 33);
        //根据class对象获取对应的成员方法
        Method method = aClass.getMethod("getName");
        //根据对象调用成员方法并打印
        //表示使用对象zhangfei调用getName方法,也就是getName方法获取姓名
        System.out.println("调用方法的返回值是:" + method.invoke(o));

        //3.使用反射机制获取类中所有成员方法
        Method[] methods = aClass.getMethods();

        for (Method m : methods){
    
    
            System.out.println("成员方法的访问修饰符是:" + m.getModifiers());
            System.out.println("成员方法的返回值类型是:" + m.getReturnType());
            System.out.println("成员方法的名称是:" + m.getName());
            System.out.println("成员方法的参数列表类型是:");
            Class<?>[] parameterTypes = m.getParameterTypes();
            for (Class cc :parameterTypes){
    
    
                System.out.println(cc + " ");
            }
            System.out.println("成员方法的异常类型列表是:");
            Class<?>[] exceptionTypes = m.getExceptionTypes();
            for (Class e: exceptionTypes){
    
    
                System.out.println(e + " ");
            }
            System.out.println("--------------------------");
        }
    }
}

6. Obtain other structural information

  • Package getPackage() Get the package information
  • Class getSuperclass() Get the inherited parent class information
  • Class[] getInterfaces() Get all the implemented interfaces
  • Annotation[] getAnnotations() Get annotation information
  • Type[] getGenericInterfaces() Get generic information
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

public class StudentTest {
    
    

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

        Class<?> aClass = Class.forName("com.lagou.teachingCase.task13.Student");
        System.out.println("获取到的包信息: " + aClass.getPackage());
        System.out.println("获取到的父类信息:" + aClass.getSuperclass());
        System.out.println("获取到的接口信息是:" );
        Class<?>[] interfaces = aClass.getInterfaces();
        for (Class c : interfaces){
    
    
            System.out.print(c + " ");
        }
        System.out.println();
        System.out.println("获取到的注解信息是:" );
        Annotation[] annotations = aClass.getAnnotations();
        for (Annotation a :annotations){
    
    
            System.out.print(a + " ");
        }
        System.out.println();
        System.out.println("获取到的泛型信息是");
        Type[] genericInterfaces = aClass.getGenericInterfaces();
        for (Type t : genericInterfaces){
    
    
            System.out.print(" " + t);
        }
        System.out.println();
    }

}

Guess you like

Origin blog.csdn.net/qq_42675807/article/details/109793650