• 69期-Java SE-023-反射-1-001-002


    ### 反射
    
    在程序运行期间获取类的结构完成某些特定的功能,一句话简单理解反射:常规情况下是通过类来创建实例化对象侧,反射就是将这一过程进行反转,通过实例化对象来获取对应类的信息。
    
    ### Class
    
    Class 是反射的源头,是专门用来描述其他类的类,Class 的每一个实例化对象都对应其他类的结构特征,Class 的构造函数是私有的,Class 类的实例化对象不能在外部创建,创建 Class 实例化对象的方式有 3 种:
    
    - 调用 Class 的静态方法 forName(String className) 创建,将目标类的全类名作为参数传入到该方法中,即可获取对应的 Class 对象。
    - 通过目标类的 class 创建,class 不是类的属性,叫做类字面量。
    - 通过目标类的实例化对象的 getClass() 方法来创建。
    
    Class 的实例化对象描述的是目标类在 JVM 内存中的运行时类,什么是运行时类?当程序启动时,目标类第一次被加载到内存中的模版就叫做运行时类,并且只加载一次。
    
    ```java
    package com.southwind.test;
    
    import com.southwind.entity.User;
    
    public class Test {
        public static void main(String[] args) {
            try {
                Class clazz1 = Class.forName("com.southwind.entity.User");
                System.out.println(clazz1);
                
                Class clazz2 = User.class;
                System.out.println(clazz2);
                
                User user = new User();
                Class clazz3 = user.getClass();
                System.out.println(clazz3);
                
                System.out.println(clazz1 == clazz2);
                System.out.println(clazz2 == clazz3);
                
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    ```
    
    
    
    #### Class 常用方法
    
    public native boolean isInterface()                                                                                            判断目标类是否为接口
    
    public native boolean isArray()                                                                                                  判断目标类是否为数组
    
    public boolean isAnnotation()                                                                                                    判断目标类是否为注解
    
    public String getName()                                                                                                            获取目标类的全类名
    
    public ClassLoader getClassLoader()                                                                                        获取类加载器
    
    public native Class getSuperclass()                                                                                            获取目标类的直接父类
    
    public Package getPackage()                                                                                                        获取目标类所在的包
    
    public String getPackageName()                                                                                                获取目标类所在包的名称
    
    public Class getInterfaces()                                                                                                            获取目标类的全部接口
    
    public native int getModifers()                                                                                                    获取目标类的访问权限修饰符
    
    public Field[] getFields()                                                    获取目标类的全部公有成员变量,包括继承自父类的和自定义的
    
    public Field getField(String name)                                    根据名称获取目标类的公有成员变量,包括继承自父类的和自定义的
    
    public Field getDeclaredField(String name)                    根据名称获取目标类的自定义成员变量
    
    public Method[] getMethods()                                        获取目标类的全部公有方法,包括继承自父类的和自定义的
    
    public Method[] getDeclaredMethods()                         获取目标类的自定义方法
    
    public Constructor[] getConstructors()                            获取目标类的公有构造函数
    
    public Constructor[] getDeclaredConstructors()            获取目标类的全部构造函数
    
    
    
    ### 通过反射获取目标类的接口信息
    
    ```java
    package com.southwind.test;
    
    public class Test2 {
        public static void main(String[] args) {
            try {
                Class clazz = Class.forName("com.southwind.entity.User");
                Class[] classArray = clazz.getInterfaces();
                for(Class cla:classArray) {
                    System.out.println(cla);
                }
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    ```
    
    
    
    ### 通过反射获取目标类的直接父类
    
    ```java
    package com.southwind.test;
    
    public class Test3 {
        public static void main(String[] args) {
            try {
                Class clazz = Class.forName("com.southwind.entity.User");
                Class superClass = clazz.getSuperclass();
                System.out.println(superClass);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    ```
    
    
    
    ### 通过反射获取目标类的构造函数
    
    ```java
    package com.southwind.test;
    
    import java.lang.reflect.Constructor;
    
    import com.southwind.entity.User;
    
    public class Test4 {
        public static void main(String[] args) {
            Class clazz = User.class;
            Constructor[] constructors = clazz.getConstructors();
            System.out.println("*********公有构造函数*********");
            for(Constructor constructor:constructors) {
                System.out.println(constructor);
            }
            
            Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
            System.out.println("*********全部构造函数*********");
            for(Constructor constructor:declaredConstructors) {
                System.out.println(constructor);
            }
            System.out.println("*********公有无参构造*********");
            try {
                Constructor constructor = clazz.getConstructor(null);
                System.out.println(constructor);
            } catch (NoSuchMethodException | SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("*********私有带参构造*********");
            try {
                Constructor declaredConstructor = clazz.getDeclaredConstructor(Long.class);
                System.out.println(declaredConstructor);
            } catch (NoSuchMethodException | SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    ```
    
    
    
    ### 通过反射获取目标类的普通方法
    
    ```java
    package com.southwind.test;
    
    import java.lang.reflect.Method;
    
    import com.southwind.entity.Student;
    
    public class Test5 {
        public static void main(String[] args) {
            Student student = new Student();
            Class clazz = student.getClass();
            System.out.println("*********公有方法*********");
            Method[] methods = clazz.getMethods();
            for(Method method:methods) {
                System.out.println(method);
            }
            System.out.println("*********本类方法*********");
            Method[] declaredMethods = clazz.getDeclaredMethods();
            for(Method method:declaredMethods) {
                System.out.println(method);
            }
            System.out.println("*********公有方法setName*********");
            try {
                Method method = clazz.getMethod("setName", String.class);
                System.out.println(method);
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("*********本类方法getName*********");
            try {
                Method declaredMethod = clazz.getDeclaredMethod("getName", null);
                System.out.println(declaredMethod);
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    }
    ```
    
    
    
    ### 通过反射获取目标类的成员变量
    
    ```java
    package com.southwind.test;
    
    import java.lang.reflect.Field;
    
    public class Test6 {
        public static void main(String[] args) {
            try {
                Class clazz = Class.forName("com.southwind.entity.Student");
                Field[] fields = clazz.getFields();
                System.out.println("*********公有成员变量*********");
                for(Field field:fields) {
                    System.out.println(field);
                }
                System.out.println("*********本类成员变量*********");
                Field[] declaredFields = clazz.getDeclaredFields();
                for(Field field:declaredFields) {
                    System.out.println(field);
                }
                System.out.println("*********公有成员变量id*********");
                Field field = clazz.getField("id");
                System.out.println(field);
                System.out.println("*********本类成员变量hobby*********");
                Field declaredField = clazz.getDeclaredField("hobby");
                System.out.println(declaredField);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    ```
    
    
    
    # 反射的应用
    
    ### 反射调用方法
    
    ```java
    package com.southwind.entity;
    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class Student{
        private Long id;
        private String name;
        public Long getId() {
            return id;
        }
        public void setId(Long id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void show() {
            System.out.println("学生信息");
            System.out.println("ID:"+this.id);
            System.out.println("姓名:"+this.name);
        }
        public static void main(String[] args) {
            Student student = new Student();
    //        student.setId(1L);
    //        student.setName("张三");
    //        student.show();
            Class clazz = Student.class;
            try {
                Method method = clazz.getDeclaredMethod("setId", Long.class);
                method.invoke(student, 1L);
                method = clazz.getDeclaredMethod("setName", String.class);
                method.invoke(student, "张三");
                method = clazz.getDeclaredMethod("show", null);
                method.invoke(student, null);
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    ```

    MyInterface.java

    package com.southwind.entity;
    
    public interface MyInterface {
    
    }

    People.java

    package com.southwind.entity;
    
    public class People {
        public int id;
        private String name;
        public void setName(String name) {
            
        }
        
        public int getId() {
            return 1;
        }
    }

    Student.java

    package com.southwind.entity;
    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class Student{
        private Long id;
        private String name;
        public Long getId() {
            return id;
        }
        public void setId(Long id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void show() {
            System.out.println("学生信息");
            System.out.println("ID:"+this.id);
            System.out.println("姓名:"+this.name);
        }
        public static void main(String[] args) {
            Student student = new Student();
    //        student.setId(1L);
    //        student.setName("张三");
    //        student.show();
            Class clazz = Student.class;
            try {
                Method method = clazz.getDeclaredMethod("setId", Long.class);
                method.invoke(student, 1L);
                method = clazz.getDeclaredMethod("setName", String.class);
                method.invoke(student, "张三");
                method = clazz.getDeclaredMethod("show", null);
                method.invoke(student, null);
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    User.java

    package com.southwind.entity;
    
    import java.io.Serializable;
    
    public class User implements MyInterface,Serializable,Comparable<String>{
        private Long id;
        private String name;
        private int age;
        public Long getId() {
            return id;
        }
        public void setId(Long id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public User(Long id, String name, int age) {
            super();
            this.id = id;
            this.name = name;
            this.age = age;
        }
        public User() {
            super();
        }
        
        private User(Long id) {
            
        }
        
        @Override
        public int compareTo(String o) {
            // TODO Auto-generated method stub
            return 0;
        }
    }

    Test.java

    package com.southwind.test;
    
    import com.southwind.entity.User;
    
    public class Test {
        public static void main(String[] args) {
            try {
                Class clazz1 = Class.forName("com.southwind.entity.User");
                System.out.println(clazz1);
                
                Class clazz2 = User.class;
                System.out.println(clazz2);
                
                User user = new User();
                Class clazz3 = user.getClass();
                System.out.println(clazz3);
                
                System.out.println(clazz1 == clazz2);
                System.out.println(clazz2 == clazz3);
                
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Test2.java

    package com.southwind.test;
    
    public class Test2 {
        public static void main(String[] args) {
            try {
                Class clazz = Class.forName("com.southwind.entity.User");
                Class[] classArray = clazz.getInterfaces();
                for(Class cla:classArray) {
                    System.out.println(cla);
                }
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Test3.java

    package com.southwind.test;
    
    public class Test3 {
        public static void main(String[] args) {
            try {
                Class clazz = Class.forName("com.southwind.entity.User");
                Class superClass = clazz.getSuperclass();
                System.out.println(superClass);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Test4.java

    package com.southwind.test;
    
    import java.lang.reflect.Constructor;
    
    import com.southwind.entity.User;
    
    public class Test4 {
        public static void main(String[] args) {
            Class clazz = User.class;
            Constructor[] constructors = clazz.getConstructors();
            System.out.println("*********公有构造函数*********");
            for(Constructor constructor:constructors) {
                System.out.println(constructor);
            }
            
            Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
            System.out.println("*********全部构造函数*********");
            for(Constructor constructor:declaredConstructors) {
                System.out.println(constructor);
            }
            System.out.println("*********公有无参构造*********");
            try {
                Constructor constructor = clazz.getConstructor(null);
                System.out.println(constructor);
            } catch (NoSuchMethodException | SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("*********私有带参构造*********");
            try {
                Constructor declaredConstructor = clazz.getDeclaredConstructor(Long.class);
                System.out.println(declaredConstructor);
            } catch (NoSuchMethodException | SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Test5.java

    package com.southwind.test;
    
    import java.lang.reflect.Method;
    
    import com.southwind.entity.Student;
    
    public class Test5 {
        public static void main(String[] args) {
            Student student = new Student();
            Class clazz = student.getClass();
            System.out.println("*********公有方法*********");
            Method[] methods = clazz.getMethods();
            for(Method method:methods) {
                System.out.println(method);
            }
            System.out.println("*********本类方法*********");
            Method[] declaredMethods = clazz.getDeclaredMethods();
            for(Method method:declaredMethods) {
                System.out.println(method);
            }
            System.out.println("*********公有方法setName*********");
            try {
                Method method = clazz.getMethod("setName", String.class);
                System.out.println(method);
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("*********本类方法getName*********");
            try {
                Method declaredMethod = clazz.getDeclaredMethod("getName", null);
                System.out.println(declaredMethod);
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    }

    Test6.java

    package com.southwind.test;
    
    import java.lang.reflect.Field;
    
    public class Test6 {
        public static void main(String[] args) {
            try {
                Class clazz = Class.forName("com.southwind.entity.Student");
                Field[] fields = clazz.getFields();
                System.out.println("*********公有成员变量*********");
                for(Field field:fields) {
                    System.out.println(field);
                }
                System.out.println("*********本类成员变量*********");
                Field[] declaredFields = clazz.getDeclaredFields();
                for(Field field:declaredFields) {
                    System.out.println(field);
                }
                System.out.println("*********公有成员变量id*********");
                Field field = clazz.getField("id");
                System.out.println(field);
                System.out.println("*********本类成员变量hobby*********");
                Field declaredField = clazz.getDeclaredField("hobby");
                System.out.println(declaredField);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    菜鸟刷题路:剑指 Offer 09. 用两个栈实现队列
    python 全栈开发,Day40(进程间通信(队列和管道),进程间的数据共享Manager,进程池Pool)
    python 全栈开发,Day39(进程同步控制(锁,信号量,事件),进程间通信(队列,生产者消费者模型))
    python 全栈开发,Day38(在python程序中的进程操作,multiprocess.Process模块)
    python 全栈开发,Day37(操作系统的发展史)
    python 全栈开发,Day36(作业讲解(大文件下载以及进度条展示),socket的更多方法介绍,验证客户端链接的合法性hmac,socketserver)
    python 全栈开发,Day35(TCP协议 粘包现象 和解决方案)
    python 全栈开发,Day34(基于UDP协议的socket)
    python 全栈开发,Day33(tcp协议和udp协议,互联网协议与osi模型,socket概念,套接字(socket)初使用)
    python 全栈开发,Day32(知识回顾,网络编程基础)
  • 原文地址:https://www.cnblogs.com/HiJackykun/p/11173257.html
Copyright © 2020-2023  润新知