• 反射机制


    1.Class类

      1.在面向对象的世界里,万事万物皆对象。

             java语言中,静态的成员,普通的数据类型不是对象

      问:类是不是对象呢?类是(哪个类的对象呢?)谁的对象呢?

      答:类也是对象,是java.lang.Class类的实例对象

      基本数据类型   void关键字  都存在类类型

    获取类类型的三种方式:

      01.类名.Class

      02.对象名.getClass();

      03.Class.forName("完整的限定名"); 推荐使用

    package com.ltc;
    /**
     * Class类的使用
     */
    public class ClassDemo1 {
    
      class Foo{
        void print(){
            System.out.println("foo");
        }
    
        public static void main(String[] args) {
            //Foo的实例对象如何表示
            Foo foo1 = new Foo();
            
            //Foo这个类 也是一个实例对象,Class类的实例对象,如何表示出来
            //任何一个类都是Class的实例对象,这个实例对象有三种表达方式
            
            //第一种表示方式==》实际再告诉我们任何一个类都有一个隐含的静态成员变量class
            Class c1 = Foo.class;
            
            //第二种表达方式 已经知道该类的对象通过getClass方法
            Class c2 = foo1.getClass();
            
            /**
             * 官网c1和c2表示了Foo类的类类型(class type)
             * 万事万物皆对象
             * 类也是对象,是Class类的实例对象
             * 这个对象我们称之为该类的类类型
             */
            
            //不管c1 or c2都代表了Foo类的类类型,一个类只可能是Class类的一个实例对象
            System.out.println(c1==c2);
            
            //第三种表达方式
            Class c3 = null;
            try {
                c3 = Class.forName("com.ltc.Foo");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                    
            System.out.println(c2==c3);
            
            //我们完全可以通过类的类类型创建该类的对象示例==》通过c1 or c2 or c3创建Foo的实例对象
            Foo foo;
            try {
                foo = (Foo)c1.newInstance();
                foo.print();
            } catch (InstantiationException | IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    java动态加载类

      Class.forName("完整限定名");

      不仅表示了类类型,还代表了动态加载类

      区分编译运行

      编译时刻加载类是静态加载类,运行时加载类是动态加载类

      new创建对象,是静态加载类,在编译时刻就需要加载所有的可能使用到的类

      通过动态加载类可以解决该问题,有效防止一个类对象加载错误导致整个程序不能运行

      功能型的

    反射:

      在运行期间,对任意一个类,我们都能知道这个类中所有的属性和方法(包括私有的)

      这种动态获取类的信息和动态调用对象的方法或者属性的功能===》java反射机制

      但是破坏了封装的安全性。

    创建一个Student对象

    package com.ltc;
    
    import java.util.Date;
    
    public class Student {
    
        public int age; // 年龄
        protected String name; // 姓名
        private char sex = '男'; // 性别
        Date birthday = new Date();// 出生日期
    
        static {
            System.out.println("这是Student类中的静态代码块!");
        }
    
        {
            System.out.println("这是Student类中的普通代码块!");
        }
    
        public Student() {
            System.out.println("这是Student类中的无参构造!");
        }
    
        // 私有的方法
        private double getSum(double num) {
            return num + 10;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public char getSex() {
            return sex;
        }
    
        public void setSex(char sex) {
            this.sex = sex;
        }
    
        public Date getBirthday() {
            return birthday;
        }
    
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
    }
    

     01.利用反射获取该类的包名、限定名he修饰符

    @org.junit.Test
        public void test01(){
            
            try {
           //动态加载类
                Class c = Class.forName("com.ltc.Student");
                
                System.out.println("所在的包名:"+c.getPackage().getName());
                System.out.println("完整限定名:"+c.getName());
                System.out.println("简写的类名:"+c.getSimpleName());
                
           //获取修饰符会返回一个int类型的数字,Modifier.toString(int num);方法把数字解析成对应的修饰符
                int num = c.getModifiers();
                String result = Modifier.toString(num);
                System.out.println("获取该类的修饰符:"+result);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }    
        }
    

    输出结果

    02.获取类的属性

    /**
         * getFileds():只能获取public修饰的属性
         * getDeclaredFields():所有属性字段的集合
         */
        @org.junit.Test
        public void test02(){
            try {
                Class c = Class.forName("com.ltc.Student");
                Field[] fields = c.getFields();
                for (int i = 0; i < fields.length; i++) {
                    System.out.println(fields[i].getName());
                    System.out.println("对应的修饰符是==》"+Modifier.toString(fields[i].getModifiers()));
                }
                System.out.println("**********************************************************");
                Field[] fields2 = c.getDeclaredFields();
                for (int i = 0; i < fields2.length; i++) {
                    System.out.println(fields2[i].getName());
                    System.out.println("对应的修饰符是==》"+Modifier.toString(fields2[i].getModifiers()));
                }
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    

    输出结果

    03.获取类的方法

    /**
         *  c.getMethods()  :获取所有public修饰的方法
         *  c.getDeclaredMethods():获取所有的方法
         */
        @org.junit.Test
        public void test03(){
            try {
                Class c = Class.forName("com.ltc.Student");
                Method[] methods = c.getDeclaredMethods();
                for (int i = 0; i < methods.length; i++) {
                    System.out.println("方法的名称==》"+methods[i].getName());
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    

    输出结果

    04.获取类的私有属性值

    @org.junit.Test
        public void test04(){
            try {
                Class c = Class.forName("com.ltc.Student");
                Student stu = (Student)c.newInstance();
                //stu.sex 获取不到私有的属性和私有方法
                Field field = c.getDeclaredField("sex");
                //打开访问私有属性或者方法的开关
                field.setAccessible(true);
                System.out.println(field.get(stu));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException 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();
            }
        }

    输出结果

    05.获取类的私有方法

       方法反射的操作
       method.invoke(对象,参数列表)

    @org.junit.Test
        public void test05(){
            
            try {
                Class c = Class.forName("com.ltc.Student");
                Student stu = (Student)c.newInstance();
                Method methods = c.getDeclaredMethod("getSum", double.class);
                methods.setAccessible(true);
                double result = (double) methods.invoke(stu, 50.0);
                System.out.println(result);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    输出结果

    升华

    @org.junit.Test
        public void test06(){
            ArrayList list = new ArrayList();
            
            ArrayList<String> list1 = new ArrayList<String>();
            list1.add("hello");
            //list1.add(20);错误的
            Class c1 = list.getClass();
            Class c2 = list1.getClass();
            System.out.println(c1 == c2);
            //反射的操作都是编译之后的操作
            
            /*
             * c1==c2结果返回true说明编译之后集合的泛型是去泛型化的
             * Java中集合的泛型,是防止错误输入的,只在编译阶段有效,
             * 绕过编译就无效了
             * 验证:我们可以通过方法的反射来操作,绕过编译
             */
            try {
                Method m = c2.getMethod("add", Object.class);
                m.invoke(list1, 20);//绕过编译操作就绕过了泛型
                System.out.println(list1.size());
                System.out.println(list1);
                /*for (String string : list1) {
                    System.out.println(string);
                }*///现在不能这样遍历
            } catch (Exception e) {
              e.printStackTrace();
            }
        }

    输出结果

  • 相关阅读:
    codebak
    (转)关于APACHE和php
    c#pda(wince)摄像头拍照程序
    C#语言实现WINCE全屏幕显示
    (转).NET反编译工具Reflector及插件
    (转)解决WebService第一次访问速度慢的问题
    (转)C#.net winform skin 皮肤大全
    python模块整理19pyMongo
    python模块整理26数据持久性pickle、shelve、SQLite
    python模块整理21multiprocessing
  • 原文地址:https://www.cnblogs.com/WillimTUrner/p/8305790.html
Copyright © 2020-2023  润新知