java - object.getClass().getDeclaredFields() 为空
问题描述
我有一个设置,我希望有一种方法来处理不同的报告模板(每个模板的字段比其他模板少/多),方法是传入报告名称并在运行时创建对象。然后它将检查每个字段是否存在,如果存在则设置值。然后该对象将被序列化为 JSON 以返回。
我有一个如下的测试设置。问题是我无法获得创建对象的字段列表。object.getClass().getDeclaredFields() 总是给出一个空数组。
想看看您是否可以发现任何错误,或者是否有更聪明的方法来做到这一点。
主要逻辑:
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
public class Test {
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException, SecurityException {
Class<?> cls = Class.forName("CustomerReservationReportBasic");
CustomerReservationReport customerReservationReport = (CustomerReservationReport) cls.getDeclaredConstructor()
.newInstance();
System.out.println(hasField(customerReservationReport, "name"));
}
public static boolean hasField(Object object, String fieldName) {
return Arrays.stream(object.getClass().getDeclaredFields()).anyMatch(f -> f.getName().equals(fieldName));
}
}
模型:
客户预订报告
这是父类,所有基本报告字段都在这里
import java.math.BigDecimal;
import lombok.Data;
@Data
public abstract class CustomerReservationReport implements Comparable<CustomerReservationReport> {
private String name;
private int num_of_visit;
private BigDecimal total_spend;
@Override
public int compareTo(CustomerReservationReport customerReservationReport) {
return this.getName().compareTo(customerReservationReport.getName());
}
}
客户预订报告基本
这将是各种报告中的一种。
public class CustomerReservationReportBasic extends CustomerReservationReport {
public CustomerReservationReportBasic() {
super();
}
}
解决方案
来自 JavadocClass::getDeclaredFields()
返回一个 Field 对象数组,反映由此 Class 对象表示的类或接口声明的所有字段。这包括公共、受保护、默认(包)访问和私有字段,但不包括继承字段。
您还需要获取对象超类的字段。
推荐阅读
- sql - 计算距离然后在SQL中找到给定纬度和经度的特定范围内的人
- javascript - 如何制作可工作的手风琴并对内容的高度和箭头符号的旋转进行动画处理?
- javascript - 使用 MVC IIS 8 错误插入文件夹 C# 发生未处理的访问异常
- perl - 如何使用 Perl 中的循环计算部分文本文件中的元素数量?
- reactjs - 多个 WordPress 插件可以添加到同一个 Gutenberg 侧边栏吗?
- javascript - 为什么我的 JWT expiresIn 值在从服务器发送到前端接收之间会发生变化?
- python - 如何根据条件编辑包含序列的数据框列?
- javascript - Javascript - “复合”类继承
- ios - 如何使用 SwiftUI 处理嵌套的 TabView?
- python - 一个程序来检查一个反转的字符串是否是回文或不在 python 中使用 Stack Machine