• 反射


    反射

      类字节码文件是在硬盘上存储的,是一个个的.class文件。我们在new一个对象时,

    JVM会先把字节码文件的信息读出来放到内存中,第二次用时,就不用再加载了,而是直接

    使用缓存的这个字节码信息。

      字节码的信息包括:类名、声明的方法、声明的字段等信息。在Java中"万物皆对象",

    这些信息当然也需要封装一个对象,这就是Class类、Method类、Field类。

      通过Class类、Method类、Field类等等类可以得到这个类型的一些信息,甚至可

    以不用new关键字就创建一个实例,可以执行一个对象中的方法,设置或获取字段的值,

    这就是反射技术

     常用方法:

    先获得class对象

    getConstructors()获取一个类的所有公共的构造方法

    getDeclaredConstructors() 获取到一个类的所有构造方法,包括私有的在内 。

    getConstructor(int.class,String.class);  // getConstructor 获取单个指定的构造方法。

    newInstance()创建一个对象

    getMethods() 获取所有 的公共方法而已。

    getDeclaredMethods(); //获取到所有的方法,但是不包含父类的方法。

    Method m = clazz.getMethod("eat", int.class);//获取指定方法
    m.invoke(p, 3); //invoke 执行一个方法。 第一个参数:方法的调用对象。 第二参数: 方法所需要的参数。

    //执行私有的方法

    m.setAccessible(true);   //设置访问权限允许访问

    getDeclaredFields()//获取 到所有的成员变量

    Field field = clazz.getDeclaredField("id"); //获取 指定的成员变量

    //设置访问权限可以访问
            field.setAccessible(true);
            field.set(p, 110); //第一个参数: 设置该数据 的成员变量, 第二个参数:属性值。
            System.out.println(p);

    1.1. Class类

    1.1.1.  获取Class对象的三种方式

      Java中有一个Class类用于代表某一个类的字节码。

      Java提供了三种方式获取类的字节码

      1.   forName()。forName方法用于加载某个类的字节码到内存中,并使用class对象进行封装

      2.   类名.class

      3.   对象.getClass()

    public class Person {
        private int id;
    
        String name;
    
        public Person(int id, String name) {
            this.id = id;
            this.name = name;
        }
    
        public Person() {
        }
    
        public void eat(int num) {
            System.out.println(name + "吃很" + num + "斤饭");
        }
    
        private static void sleep(int num) {
            System.out.println("明天睡上" + num + "小时");
        }
    
        public static void sum(int[] arr) {
            System.out.println("长度是:" + arr.length);
        }
    
        @Override
        public String toString() {
            return " 编号:" + this.id + " 姓名:" + this.name;
        }
    }
    /*
    反射: 当一个字节码文件加载到内存的时候,jvm会对该字节码进行解剖,然后会创建一个对象的Class对象,把字节码文件的信息全部都
    存储到该Class对象中,我们只要获取到Class对象,我们就可以使用字节码对象设置对象的属性或者调用对象的方法等操作....
    
    注意: 在反射技术中一个类的任何成员都有对应 的类进行描述。  比如:  成员变量(Field)   方法----> Method类  
    
    */
    public class Demo1 {
        Person p;
        public static void main(String[] args) throws ClassNotFoundException {
            //Person p = new Person(110,"狗娃");
            
            //推荐使用: 获取Class对象的方式一
            Class clazz1 = Class.forName("com.it.reflect.Person");
            System.out.println("clazz1:"+ clazz1);
            
            
            //获取Class对象的方式二: 通过类名获取
            Class clazz2 = Person.class;
            System.out.println("clazz1==clazz2?"+ (clazz1==clazz2));
            
            
            //获取Class对象的方式三 :通过对象获取
            Class clazz3 = new Person(110,"狗娃").getClass();
            System.out.println("clazz2==clazz3?"+ (clazz2==clazz3));
            
        }
        
    }

    1.1.2.  通过Class类获取类型的一些信息

       1. getName()类的名称(全名,全限定名)

       2 getSimpleName()类的的简单名称(不带包名)

       3. getModifiers(); 类的的修饰符

       4.创建对象

          无参数构造创建对象

          newInstance()

       5.getConstructors()获取一个类的所有公共的构造方法

       6. 获取指定参数的构造器对象,并可以使用Constructor对象创建一个实例

        

          Constructor<T> getConstructor(Class<?>... parameterTypes)

    /**
         * 通过Class对象获取类的一些信息
         * 
         * @throws Exception
         * */
        private static void test2() throws Exception {
            Class clazz1 = Class.forName("cn.itcast.gz.reflect.Person");
            // 获取类的名称
            String name = clazz1.getName();
            System.out.println(name); // cn.itcast.gz.reflect.Person
            // 获取类的简单名称
            System.out.println(clazz1.getSimpleName()); // Person
            // 获取类的修饰符
            int modifiers = clazz1.getModifiers();
            System.out.println(modifiers);
            // 构建对象(默认调用无参数构造.)
            Object ins = clazz1.newInstance();
            Person p = (Person) ins;
            System.out.println(p); // cn.itcast.gz.reflect.Person@c17164
            // 获取指定参数的构造函数
            Constructor<?> con = clazz1.getConstructor(String.class, int.class);
            // 使用Constructor创建对象.
            Object p1 = con.newInstance("jack", 28);
            System.out.println(((Person) p1).getName());
        }

    1.1.3.  通过Class类获取类型中的方法的信息

      1.获取公共方法包括继承的父类的方法

            getMethods()返回一个数组,元素类型是Method

    /**
         * 获取公有方法.
         * @throws Exception
         * */
        private static void test3() throws Exception {
            Class clazz1 = Class.forName("cn.itcast.gz.reflect.Person");
            // 1.获取非私用方法(包括父类继承的方法)
            Method[] methods = clazz1.getMethods();
            System.out.println(methods.length);
            for (Method m : methods) {
                // System.out.println(m.getName());
                if ("eat".equals(m.getName())) {
                    m.invoke(clazz1.newInstance(), null);
                }
            }
    
        }

      2.获取指定参数的公共方法

            getMethod("setName", String.class);

    /**
         * 获取指定方法签名的方法
         * 
         * @throws Exception
         * */
        private static void test4() throws Exception {
            Class clazz1 = Class.forName("cn.itcast.gz.reflect.Person");
            // 获取指定名称的函数
            Method method1 = clazz1.getMethod("eat", null);
            method1.invoke(new Person(), null);
        }
    /**
         * 获取指定方法名且有参数的方法
         * 
         * @throws Exception
         * */
        private static void test5() throws Exception {
            Class clazz1 = Class.forName("cn.itcast.gz.reflect.Person");
            Method method = clazz1.getMethod("eat", String.class);
            method.invoke(new Person(), "包子");
        }
    
        /**
         * 获取指定方法名,参数列表为空的方法.
         * 
         * @throws Exception
         * */
        private static void test4() throws Exception {
            Class clazz1 = Class.forName("cn.itcast.gz.reflect.Person");
            // 获取指定名称的函数
            Method method1 = clazz1.getMethod("eat", null);
            method1.invoke(new Person(), null);
        }

      3.获得所有的方法,包括私有

            Method[] getDeclaredMethods() 

    /**
         * 反射静态方法
         * @throws Exception
         * */
        private static void test7() throws Exception {
            Class clazz1 = Class.forName("cn.itcast.gz.reflect.Person");
            Method method = clazz1.getMethod("play", null);
            method.invoke(null, null);
        }
    
        /**
         * 访问私有方法 暴力反射
         * @throws Exception
         * */
        private static void test6() throws Exception {
            Class clazz1 = Class.forName("cn.itcast.gz.reflect.Person");
            Method method = clazz1.getDeclaredMethod("movie", String.class);
            method.setAccessible(true);
            method.invoke(new Person(), "苍老师");
        }

      4.获得指定参数的方法,包括私有

            Method getDeclaredMethod(String name, Class<?>... parameterTypes)

    1.1.4.  通过Class类获取类型中的字段的信息

      1.获取公共字段

          Field[] getFields() 

      2.获取指定参数的公共字段

          Field getField(String name) 

    /**
         * 获取公有的字段
         * */
        private static void test8() throws Exception {
            Class clazz1 = Class.forName("cn.itcast.gz.reflect.Person");
            Field[] fields = clazz1.getFields();
            Person p = new Person();
            System.out.println(fields.length);
            for (Field f : fields) {
                System.out.println(f.getName());
                if ("name".equals(f.getName())) {
                    System.out.println(f.getType().getName());
                    f.set(p, "jack");
                }
            }
            System.out.println(p.getName());
    
        }

      3.获取所有的字段

          Field[] getDeclaredFields() 

      4.获取指定参数的字段,包括私用

          Field getDeclaredField(String name) 

    /**
         * 获取私有的字段
         * @throws Exception
         * */
        private static void test9() throws Exception {
            Class clazz1 = Class.forName("cn.itcast.gz.reflect.Person");
            Field field = clazz1.getDeclaredField("age");
            System.out.println(field.getName());
            field.setAccessible(true);
            Person p = new Person();
            field.set(p, 100);
            System.out.println(p.getAge());
        }
  • 相关阅读:
    一键编译go文件命令.bat
    安装go语言,配置环境及IDE,只需3步
    Mysql show Status常用参数详解
    LFS:kernel panic VFS: Unable to mount root fs
    LFS: Interface eth0 doesn't exist
    转:Xshell显示找不到匹配的outgoing encryption算法怎么办
    NTP-ntpdate:no server suitable for synchronization found
    linux/module.h: No such file or directory 内核模块编译过程
    ASCII码表完整版
    [Firmware Warn]: GHES: Failed to read error status block address for hardware error source
  • 原文地址:https://www.cnblogs.com/loveincode/p/5342931.html
Copyright © 2020-2023  润新知