object.getClass().getDeclaredFields() 为空,java,json,reflection"/>

首页 > 解决方案 > 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();
    }
}

标签: javajsonreflection

解决方案


来自 JavadocClass::getDeclaredFields()

返回一个 Field 对象数组,反映由此 Class 对象表示的类或接口声明的所有字段。这包括公共、受保护、默认(包)访问和私有字段,但不包括继承字段

您还需要获取对象超类的字段。


推荐阅读