Java — 反射

程序在运行中也可以获取类的变量和方法信息,并通过获取到的信息来创建对象。程序不必再编译期就完成确定,在运行期仍然可以扩展。

示例:学生类

public class Student {
    // 成员变量:公共、受保护、默认、私有各一个
    public String name;
    protected String pwd;
    String sex;
    private int age;

    // 构造方法:公共两个,受保护、默认、私有各一个
    public Student() {
    }

    protected Student(String name) {
        this.name = name;
    }

    Student(String name, String pwd) {
        this.name = name;
        this.pwd = pwd;
    }

    private Student(String name, String pwd, String sex) {
        this.name = name;
        this.pwd = pwd;
        this.sex = sex;
    }

    public Student(String name, String pwd, String sex, int age) {
        this.name = name;
        this.pwd = pwd;
        this.sex = sex;
        this.age = age;
    }

    // 成员方法:公共、受保护、默认、私有各一个
    public void method1() {
        System.out.println("public成员方法:method1");
    }

    protected void method2() {
        System.out.println("protected成员方法:method2");
    }

    void method3() {
        System.out.println("default成员方法:method3");
    }

    private void method4() {
        System.out.println("private成员方法:method4");
    }

    @Override
    public String toString() {
        return "Student{" + "name='" + name + '\'' + ", pwd='" + pwd + '\'' + ", sex=" + sex + ", age=" + age + '}';
    }
}

类名: Class<t></t>

包名: java.lang.Class<t></t>

Class 类和 Class 文件的关系: java.lang.Class &#x7C7B;&#x7528;&#x4E8E;&#x8868;&#x793A;&#x4E00;&#x4E2A;&#x7C7B;&#x7684;&#x5B57;&#x8282;&#x7801;&#xFF08;.class&#xFF09;&#x6587;&#x4EF6;

通过反射获取对象的方式有以下三种:

方式 描述 类名.class 当该类被加载成 .class 文件时,此时该类变成了 .class,再获取该字节码文件对象,也就是获取自己, 该类处于字节码阶段 对象.getClass() 通过类的实例获取该类的字节码文件对象,该类处于创建对象阶段 Class.forName(“全限定类名”) 通过 Class 类中的静态方法 forName 直接获取到该类的字节码文件对象,此时该类还是源文件阶段,并没有变为字节码文件

测试:

public class Test_01 {
    public static void main(String[] args) throws ClassNotFoundException {
        // 类名.class
        Class s1 = Student.class;

        // 对象.getClass()
        Student student = new Student();
        Class s2 = student.getClass();

        // Class.forName("包名.类名")
        Class s3 = Class.forName("A_11_reflect.Student");

        System.out.println(s1 + "\n" + s2 + "\n" + s3);
        System.out.println(s1 == s2 && s1 == s3 && s2 == s3);
    }
}

运行:

class A_11_reflect.Student
class A_11_reflect.Student
class A_11_reflect.Student
true

3.1、获取构造方法

修饰符和类型 方法 秒速 Constructor[] getConstructors() 返回该类所有的公共构造方法 Constructor getConstructor(Class… parameterTypes) 返回该类指定的公共构造方法 Constructor[] getDeclaredConstructors() 返回该类所有的构造方法 Constructor getDeclaredConstructor(Class… parameterTypes) 返回该类指定的构造方法

测试:

public class Test_02 {
    public static void main(String[] args) throws NoSuchMethodException {
        Class s = Student.class;

        // 获取该类所有的公共构造方法
        Constructor[] constructors = s.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println("constructor = " + constructor);
        }
        System.out.println("--------");

        // 获取该类指定的公共构造方法
        Constructor c1 = s.getConstructor();
        Constructor c2 = s.getConstructor(String.class, String.class, String.class, int.class);
        System.out.println("c1 = " + c1);
        System.out.println("c2 = " + c2);
        System.out.println("--------");

        // 获取该类所有的构造方法
        Constructor[] declaredConstructors = s.getDeclaredConstructors();
        for (Constructor declaredConstructor : declaredConstructors) {
            System.out.println("declaredConstructor = " + declaredConstructor);
        }
        System.out.println("--------");

        // 获取该类指定的构造方法
        Constructor c3 = s.getDeclaredConstructor();
        Constructor c4 = s.getDeclaredConstructor(String.class);
        Constructor c5 = s.getDeclaredConstructor(String.class, String.class);
        Constructor c6 = s.getDeclaredConstructor(String.class, String.class, String.class);
        Constructor c7 = s.getDeclaredConstructor(String.class, String.class, String.class, int.class);
        System.out.println("c3 = " + c3 + "\nc4 = " + c4 + "\nc5 = " + c5 + "\nc6 = " + c6 + "\nc7 = " + c7);
    }
}

运行:

constructor = public A_11_reflect.Student(java.lang.String,java.lang.String,java.lang.String,int)
constructor = public A_11_reflect.Student()
declaredConstructor = public A_11_reflect.Student(java.lang.String,java.lang.String,java.lang.String,int)
declaredConstructor = private A_11_reflect.Student(java.lang.String,java.lang.String,java.lang.String)
declaredConstructor = A_11_reflect.Student(java.lang.String,java.lang.String)
declaredConstructor = protected A_11_reflect.Student(java.lang.String)
declaredConstructor = public A_11_reflect.Student()
name1 = public java.lang.String A_11_reflect.Student.name
name = public java.lang.String A_11_reflect.Student.name
pwd = protected java.lang.String A_11_reflect.Student.pwd
sex = java.lang.String A_11_reflect.Student.sex
age = private int A_11_reflect.Student.age

4.2、调用成员变量

类名: Field

包名: java.lang.reflect.Field

修饰符和类型 成员方法 描述 Object set(Object obj, Object value) 将 value 赋值给 obj 对象的成员变量 Object get(Object obj) 返回 obj 对象的成员变量值

测试:

public class Test_05 {
    public static void main(String[] args) throws Exception {
        Class s = Student.class;
        // 先获取所有成员变量
        Field name = s.getDeclaredField("name");
        Field pwd = s.getDeclaredField("pwd");
        Field sex = s.getDeclaredField("sex");
        Field age = s.getDeclaredField("age");
        // 调用无参构造方法
        Constructor c = s.getConstructor();
        // 实例化
        Student student = c.newInstance();
        // 成员变量赋值
        name.set(student, "张三");
        pwd.set(student, "123");
        sex.set(student, "男");
        age.setAccessible(true); // 私有成员需取消访问检查
        age.set(student, 23);
        System.out.println("student = " + student);
        System.out.println("--------");
        // 获取成员变量值
        System.out.println(name.get(student));
        System.out.println(pwd.get(student));
        System.out.println(sex.get(student));
        System.out.println(age.get(student));
    }
}

运行:

student = Student{name='张三', pwd='123', sex=男, age=23}
method1 = public void A_11_reflect.Student.method1()
method1 = public void A_11_reflect.Student.method1()
method2 = protected void A_11_reflect.Student.method2()
method3 = void A_11_reflect.Student.method3()
method4 = private void A_11_reflect.Student.method4()

5.2、调用成员方法

类名: Method

包名: java.lang.reflect.Method

修饰符和类型 成员方法 描述 Object invoke(Object obj, Object… args) obj:调用方法的对象,args:方法的参数

测试:

public class Test_07 {
    public static void main(String[] args) throws Exception {
        Class s = Student.class;
        // 获取类的无参构造方法
        Constructor constructor = s.getConstructor();
        // 实例化
        Student student = constructor.newInstance();
        // 调用方法
        Method[] declaredMethods = s.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            declaredMethod.setAccessible(true); // 取消私有成员方法访问检查
            declaredMethod.invoke(student);
        }
    }
}

运行:

protected成员方法:method2
default成员方法:method3
private成员方法:method4
public成员方法:method1

6.1、示例1

需求:往 ArrayList<integer></integer> 集合中添加字符串数据。

示例:

// 越过泛型检查
public class Test_08 {
    public static void main(String[] args) throws Exception {
        ArrayList arrayList = new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        System.out.println("arrayList = " + arrayList);
        Class arrayListClass = arrayList.getClass();
        Method add = arrayListClass.getMethod("add", Object.class);
        add.invoke(arrayList, "张三");
        add.invoke(arrayList, "李四");
        add.invoke(arrayList, "王五");
        System.out.println("arrayList = " + arrayList);
    }
}

运行:

arrayList = [1, 2, 3]
arrayList = [1, 2, 3, 张三, 李四, 王五]

6.2、示例2

需求:通过 properties.txt 配置文件运行类中的方法。

示例:

className=A_11_reflect/demo/Student
methodName=study
parameter=张三
public class Student {
    public void study(String name) {
        System.out.println(name + "同学爱学习!");
    }
}
public class Teacher {
    public void study(String name) {
        System.out.println(name + "老师爱学习!");
    }
}

测试:

public class Test_01 {
    public static void main(String[] args) throws Exception {
        // 加载数据
        Properties p = new Properties();
        // 读取配置
        FileReader fr = new FileReader(".\\properties.txt");
        p.load(fr);
        fr.close();

        // 获取类名
        String className = p.getProperty("className");
        // 获取方法名
        String methodName = p.getProperty("methodName");
        // 获取参数
        String parameter = p.getProperty("parameter");

        // 反射获取类的实例
        Class clazz = Class.forName(className);
        // 获取类的构造方法
        Constructor con = clazz.getConstructor();
        // 类实例化
        Object o = con.newInstance();
        // 获取方法对象,指定参数类型
        Method m = clazz.getMethod(methodName, String.class);
        // o对象调用m方法传入parameter参数
        m.invoke(o, parameter);
        System.out.println("o = " + o);
    }
}

运行:

张三同学爱学习!

Original: https://www.cnblogs.com/bybeiya/p/16251826.html
Author: 北涯
Title: Java — 反射

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/585897/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 【设计模式】Java设计模式-享元模式

    Java设计模式 – 享元模式 😄 不断学习才是王道🔥 继续踏上学习之路,学之分享笔记👊 总有一天我也能像各位大佬一样🏆原创作品,更多关注我CSDN: 一个有梦有戏的人…

    Linux 2023年6月6日
    0140
  • 操作系统实战45讲- 02 几行汇编几行C:实现一个最简单的内核

    本节源代码位置https://gitee.com/lmos/cosmos/tree/master/lesson02/HelloOS Hello OS 之前,我们先要搞清楚 Hell…

    Linux 2023年6月7日
    0101
  • NoteOfMySQL-13-事务与并发控制

    一、事务简介 存储引擎如InnoDB、BDB才支持事务处理。 每个事务(transaction)的处理必须满足ACID原则: 原子性(Atomicity): 原子性指每个事务都必须…

    Linux 2023年6月14日
    0132
  • Nginx笔记

    实现负载均衡 这里采用的是权重 进入配置文件目录cd /usr/local/nginx/conf/ //实际根据自己的目录来 编辑vim nginx.conf 这段代码上方加入自定…

    Linux 2023年6月14日
    0109
  • shell join详解

    首先贴一个,join –help 然后来理解下。 join 【命令选项】 文件1 文件2 //命令选项可以很多, 但文件只能是两个 先从重要的开始说,join 的作用是…

    Linux 2023年5月28日
    079
  • Linux常用磁盘管理命令详解

    du du命令用于查看文件和目录磁盘的使用空间。 命令语法: du [&#x53C2;&#x6570;] [&#x6587;&#x4EF6;&amp…

    Linux 2023年5月27日
    0113
  • Linux账户,组,权限管理

    内容多数来源于https://wangchujiang.com/linux-command/c/chmod.html, 开源地址:https://github.com/jaywcj…

    Linux 2023年6月7日
    088
  • CentOS7下安装python3.7

    以原码编译的方式安装 1.官网下载python3.7软件包 2.上传至Linux中,并解压 tar -zxvf python-3.7.2.tgz 3.安装gcc和python所需依…

    Linux 2023年6月6日
    094
  • ERROR: Exception when publishing, exception message [Failed to connect and initialize SSH connection

    jenkins 在构建时连接其他部署节点的服务器时报错,ERROR: Exception when publishing, exception message [Failed to…

    Linux 2023年6月14日
    095
  • DOS-批处理隐藏自身窗口

    批处理隐藏运行效果代码,防止出现黑窗口不建议非法用途,可以用来执行命令,提供用户体验。 运行bat时隐藏cmd窗口的方法 运行bat时隐藏cmd窗口的方法 可以编辑一个vbs脚本,…

    Linux 2023年6月8日
    0115
  • 复习刷题7.23-Java开发

    基本上是每天学一点点 在复习的同时,发现好多之前没学过的,底层基础是真的重要(主要是算法不行(x))。开始狂补了要。 书:图解http,Java编程思想,疯狂Java讲义,计算机网…

    Linux 2023年6月7日
    075
  • 同城双活-流量分流

    引言 现阶段,在同城带宽时延问题没有经过大规模的生产实践、验证的情况下,我们只导入”白名单或1%”的小比例请求流量,进入双活环境,确保环境有效的(活的),同…

    Linux 2023年6月14日
    0106
  • Linux 批量杀死进程(详细版本)

    使用场景 当程序中有使用到多进程且进程数较多的情况,如下图,且需要通过控制台杀死所有的 GSM_run.py 的进程时,利用 kill 命令一个一个的去结束进程是及其耗时且繁琐的,…

    Linux 2023年6月7日
    0152
  • 01-MySQL连接查询、聚合函数

    1、连接查询 1.1、左连接 以左表为基准进行查询,左表数据回全部显示出来 右表中如果匹配连接条件的数据则显示相应字段的数据,如果不匹配,则显示为NULL 1.2、右连接 以右表为…

    Linux 2023年6月7日
    0130
  • 【Docker搭建】2. 在Docker中安装Redis5.0

    1. 安装Docker,详细 请看安装教程 。若已安装,请看 2. 2. 拉取 Redis 镜像 docker pull redis:5.0.5 3. 设置 Redis 配置文件 …

    Linux 2023年6月13日
    092
  • POJ1611(The Suspects)–简单并查集

    1 #include 2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include&lt…

    Linux 2023年6月7日
    0115
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球