当前位置: 首页 > news >正文

Java - 通过反射进行赋值以及函数调用

Java - 通过反射进行赋值以及函数调用

  • 前言
  • 一. 通过反射进行赋值
    • 1.1 测试
    • 1.2 总结
  • 二. 通过反射进行函数调用

前言

说来惭愧,虽然反射在Java中是非常重要和常见的一种机制。但是,每当自己去写这方面的代码的时候,总是容易愣住。还得想一想代码怎么写。因此写下这篇文章做个笔记。

可以先看下这篇文章 Java-通过反射来打印类

一. 通过反射进行赋值

1.我们准备一个Teacher类,并把相关的属性都设置为private私有。准备他的get函数,set就不必啦。

public class Teacher {
    private int userId;
    private String userName;

    public int getUserId() {
        return userId;
    }

    public String getUserName() {
        return userName;
    }

    private void hello(String name, Integer userId) {
        System.out.println("Hello World," + name + ", " + userId);
    }
}

那么我们如何通过反射来进行赋值呢?关键代码:拿到这个类中的字段。

Field fieldName= xxx.class.getDeclaredField("fieldName");

1.1 测试

测试1:

@org.junit.Test
public void test3() throws Exception {
    Teacher teacher = new Teacher();
    Field userName = Teacher.class.getDeclaredField("userName");
    // 授权访问私有成员变量
    userName.setAccessible(true);
    userName.set(teacher, "ljj");
    System.out.println(teacher.getUserName());:
    System.out.println(teacher.getUserId());
}

结果如下:可见userId输出为0。因为我们没有对它进行赋值。所以初始值为0,而userName则赋值成功。
在这里插入图片描述
测试2:setAccessible我们设置为false(默认)

@org.junit.Test
public void test3() throws Exception {
    Teacher teacher = new Teacher();
    System.out.println(teacher.getUserId());
    Field userId = Teacher.class.getDeclaredField("userId");
    userId.setAccessible(false);
    userId.set(teacher, 10);
    System.out.println(teacher.getUserId());
}

结果如下:
在这里插入图片描述
测试3:setAccessible设置为true,然后再次赋值userId

@org.junit.Test
public void test3() throws Exception {
    Teacher teacher = new Teacher();
    System.out.println(teacher.getUserId());
    Field userId = Teacher.class.getDeclaredField("userId");
    userId.setAccessible(true);
    userId.set(teacher, 10);
    System.out.println(teacher.getUserId());
}

结果如下:
在这里插入图片描述
测试4:给Teacher加一个public类型的属性address

public String address;
public String getAddress() {
    return address;
}

测试如下:

@org.junit.Test
public void test3() throws Exception {
    Teacher teacher = new Teacher();
    Field address = Teacher.class.getDeclaredField("address");
    address.set(teacher, "abcd");
    System.out.println(teacher.getAddress());
}

结果:
在这里插入图片描述

1.2 总结

  1. 可以通过Field name= Object.class.getDeclaredField("name");的方式拿到类的字段。
  2. 通过name.set(Target, value);进行属性的赋值。
  3. 如果字段是私有的,还需要设置setAccessible(true); 其他不需要。

二. 通过反射进行函数调用

关键代码:

Method method = Teacher.class.getDeclaredMethod(方法名称, 参数类型1.class, 参数类型2.class,...);

以本文案例为例:

private void hello(String name, Integer userId) {
    System.out.println("Hello World," + name + ", " + userId);
}

那么不难写出代码如下:

@org.junit.Test
public void test3() throws Exception {
    Teacher teacher = new Teacher();
    // 写对方法名称、参数类型
    Method hello = Teacher.class.getDeclaredMethod("hello", String.class, Integer.class);
    // 因为是私有的,所以要想访问,需要设置Accessible
    hello.setAccessible(true);
    // 对应的参数
    Object[] objects = {"LJJ", 24};
    // 调用函数
    hello.invoke(teacher, objects);
}

结果如下:
在这里插入图片描述

相关文章:

  • OpUtils的网络扫描
  • 电力系统潮流计算(牛顿-拉夫逊法、高斯-赛德尔法、快速解耦法)【6节点 9节点 14节点 26节点 30节点 57节点】(Matlab代码实现)
  • Kafka消息队列大数据实战教程-第四篇(Kafka客户端Producer API)
  • 【从零开始学习深度学习】12. 什么是模型的训练误差?基于三阶多项式的欠拟合与过拟合训练过程演示
  • 腾讯数字孪生和To B简介
  • 【机器学习】Rasa NLU以及Rasa Core概念和语法简介(超详细必看)
  • OkHttp3 详解
  • java计算机毕业设计ssm线上拍卖系统设计6luor(附源码、数据库)
  • idea远程debug
  • CRC 循环冗余检验【计网必考】
  • 《Nuitka打包实战指南》实战打包Playwright
  • 搜题接口系统
  • 极客时间Kafka - 05 Kafka 生产者发送消息可靠性保障|幂等生产者和事务生产者
  • Springboot 使用 Mybatis 启动失败排查定位
  • java-net-php-python-springbot学生奖惩管理系统计算机毕业设计程序
  • 国美被曝出员工讨债,与管理层起风波 黄光裕“廉颇老矣”
  • 【数据库系统】视图
  • Java关于普通查找和二分查找
  • 自定义网页中被选中文本的样式 CSS selection
  • 第五章 使用管理门户监控 - 监控日志
  • 电加热油锅炉工作原理_电加热导油
  • 大型电蒸汽锅炉_工业电阻炉
  • 燃气蒸汽锅炉的分类_大连生物质蒸汽锅炉
  • 天津市维修锅炉_锅炉汽化处理方法
  • 蒸汽汽锅炉厂家_延安锅炉厂家
  • 山西热水锅炉厂家_酒店热水 锅炉
  • 蒸汽锅炉生产厂家_燃油蒸汽发生器
  • 燃煤锅炉烧热水_张家口 淘汰取缔燃煤锅炉
  • 生物质锅炉_炉
  • 锅炉天然气_天燃气热风炉