zoukankan      html  css  js  c++  java
  • Java核心技术笔记——第 12 章 反射

    转载自:[https://www.cnblogs.com/chanshuyi/p/head_first_of_reflection.html]

    12 反射

    1. 引入反射

    通常情况下,调用一个类的方法的步骤如下:

    1. 创建该类的对象。
    2. 调用该对象的方法。

    通过这种方式调用方法时,必须要知道类的定义以及类的所有属性和方法。代码如下:

    Apple apple = new Apple(); //直接初始化,「正射」
    apple.setPrice(4);
    

    另一种调用类方法的方式是:反射。示例如下:

    //获取类的class对象
    Class clz = Class.forName("com.chenshuyi.reflect.Apple");
    //获取类的指定方法的method对象
    Method method = clz.getMethod("setPrice", int.class);
    //获取类的默认构造器
    Constructor constructor = clz.getConstructor();
    //创建类的对象
    Object object = constructor.newInstance();
    //调用方法
    method.invoke(object, 4);
    

    上面两段代码的执行结果,其实是完全一样的。但是其思路完全不一样,第一段代码在未运行时就已经确定了要运行的类(Apple),而第二段代码则是在运行时通过字符串值才得知要运行的类(com.chenshuyi.reflect.Apple )。

    2. 反射定义

    反射就是在运行时才知道要操作的类是什么,并且可以在运行时获取类的完整构造,并调用对应的方法。

    3. 示例的完整代码

    public class Apple {
        private int price;
        public int getPrice(){
            return price;
        }
        public void setPrice(int price) {
            this.price = price;
        }
        public static void main(String[] args) throws Exception{
            //正常的调用
            Apple apple = new Apple();
            apple.setPrice(5);
            System.out.println("Apple Price:" + apple.getPrice());
            //使用反射调用
            Class clz = Class.forName("com.chenshuyi.api.Apple");
            Method setPriceMethod = clz.getMethod("setPrice", int.class);
            Constructor appleConstructor = clz.getConstructor();
            Object appleObj = appleConstructor.newInstance();
            setPriceMethod.invoke(appleObj, 14);
            Method getPriceMethod = clz.getMethod("getPrice");
            System.out.println("Apple Price:" + getPriceMethod.invoke(appleObj));
        }
    }
    

    4. 反射调用的步骤

    一般情况下我们使用反射获取一个对象的步骤:

    1. 获取类的 Class 对象实例

      Class clz = Class.forName("com.zhenai.api.Apple");
      
    2. 根据 Class 对象实例获取 Constructor 对象

      Constructor appleConstructor = clz.getConstructor();
      
    3. 使用 Constructor 对象的 newInstance 方法获取反射类对象

      Object appleObj = appleConstructor.newInstance();
      

    如果要调用某一个方法,则需要经过下面的步骤:

    1. 获取方法的 Method 对象

      Method setPriceMethod = clz.getMethod("setPrice", int.class);
      
    2. 利用 invoke 方法调用方法

      setPriceMethod.invoke(appleObj, 14);
      

    5. 反射常用的 API

    1. 获取反射中的 Class 对象

    在反射中,要获取一个类或调用一个类的方法,我们首先需要获取到该类的 Class 对象。在 Java API 中,获取 Class 类对象有三种方法:

    • 使用 Class.forName 静态方法。当你知道类的全路径名时,你可以使用该方法获取 Class 类对象。

      Class clz = Class.forName("java.lang.String"); 
      
    • 使用 类型名.class 。

      Class clz = String.class;
      
    • 使用类对象的 getClass() 方法。

      String str = new String("Hello");
      Class clz = str.getClass();
      

    2. 通过反射创建类对象

    通过反射创建类对象主要有两种方式(newInstance() 的返回值是 Object):

    • 通过 Class 对象的 newInstance() 方法

      Class clz = Apple.class;
      Apple apple = (Apple)clz.newInstance();
      
    • 通过 Constructor 对象的 newInstance() 方法。

      Class clz = Apple.class;
      Constructor constructor = clz.getConstructor();
      Apple apple = (Apple)constructor.newInstance();
      

    通过 Constructor 对象创建类对象可以选择特定构造方法,而通过 Class 对象则只能使用默认的无参数构造方法。下面的代码就调用了一个有参数的构造方法进行了类对象的初始化:

    Class clz = Apple.class;
    Constructor constructor = clz.getConstructor(String.class, int.class);
    Apple apple = (Apple)constructor.newInstance("红富士", 15);
    

    3. 通过反射获取类属性、方法、构造器

    获取类的属性

    • Field getField(String name):获取 Class 对象对应类的指定公有属性。
    • Field[] getFields() :获取 Class 对象对应类的所有公有属性(包括从父类中继承的公有属性),无法获取类的私有属性。
    • Field[] getDeclaredFields() :获取 Class 对象对应类的所有属性(仅限本类中定义的公有、默认、保护、私有属性,不包括从父类中继承的属性)。
    • Field getDeclaredField(String name):获取 Class 对象对应类的指定属性(仅限本类中定义的公有或默认或保护或私有属性,不包括从父类中继承的属性)。

    获取类的方法

    • Method getMethod(String name, Class<?>... parameterTypes):获取 Class 对象对应类的指定公有方法。
    • Method[] getMethods(): 获取 Class 对象对应类的所有公有方法(包括从父类中继承的公有方法),无法获取类的私有方法。
    • Method[] getDeclaredMethods():获取 Class 对象对应类的所有方法(仅限本类中定义的公有、默认、保护、私有方法,不包括从父类中继承的方法,以及本类的构造器)。
    • Method getDeclaredMethod(String name, Class<?>... parameterTypes):获取 Class 对象对应类的指定公有方法(仅限本类中定义的公有或默认或保护或私有方法,不包括从父类中继承的方法)。

    获取类的构造器

    • Constructor<T> getConstructor(Class<?>... parameterTypes):获取 Class 对象对应类的指定公有构造器。
    • Constructor<?>[] getConstructors() :获取 Class 对象对应类的所有公有构造器。
    • Constructor<?>[] getDeclaredConstructors() :获取 Class 对象对应类的所有构造器。
    • Constructor<?>[] getDeclaredConstructor(Class<?>... parameterTypes) :获取 Class 对象对应类的指定构造器(公有或私有)。
  • 相关阅读:
    前端常用插件收藏文章
    vue+ts修改父组件属性的写法。
    JS new date在IOS出现的问题
    js 和各种屏幕高度的写法
    react 配置ant时遇见的一个Error: Multiple configuration files found. Please remove one: – package.json#babel – .babelrc 解决方案
    vue 的sync用法
    VUE Right-hand side of ‘instanceof’ is not an object 解决方案
    记录一下navicat的快捷键
    什么是servlet(转)
    Java位运算在程序设计中的使用:位掩码(BitMask)
  • 原文地址:https://www.cnblogs.com/echie/p/9785676.html
Copyright © 2011-2022 走看看