Java 反射动态访问实体类属性:zdy1-zdy50 的 get 和 set 方法

假设你有一个 Java 实体类,其中包含名为 'zdy1' 到 'zdy50' 的属性。如何编写代码,方便地获取和设置这些属性的值呢?

使用反射来实现!

以下是示例代码:

public class MyClass {
    private String zdy1;
    private String zdy2;
    // ...
    private String zdy50;

    public String getZdy(int i) throws NoSuchFieldException, IllegalAccessException {
        Field field = getClass().getDeclaredField('zdy' + i);
        field.setAccessible(true);
        return (String) field.get(this);
    }

    public void setZdy(int i, String value) throws NoSuchFieldException, IllegalAccessException {
        Field field = getClass().getDeclaredField('zdy' + i);
        field.setAccessible(true);
        field.set(this, value);
    }
}

使用示例:

MyClass obj = new MyClass();
obj.setZdy(1, 'hello');
String zdy1 = obj.getZdy(1);
System.out.println(zdy1); // 输出 hello

代码解释:

  1. getZdy(int i) 方法

    • 使用 getClass().getDeclaredField('zdy' + i) 获取名为 'zdy' + i 的属性字段。
    • 使用 field.setAccessible(true) 允许访问私有属性。
    • 使用 field.get(this) 获取该属性的值,并强制转换为 String 类型。
  2. setZdy(int i, String value) 方法

    • 使用 getClass().getDeclaredField('zdy' + i) 获取名为 'zdy' + i 的属性字段。
    • 使用 field.setAccessible(true) 允许访问私有属性。
    • 使用 field.set(this, value) 设置该属性的值。

总结:

通过反射机制,我们可以动态地访问和设置实体类中任意属性的值,简化代码并提高代码的可读性。当然,反射的使用也需要注意其带来的性能问题,需要谨慎使用。


原文地址: https://www.cveoy.top/t/topic/nPaU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录