有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

json<Java反射>对象。getClass()。getDeclaredFields()为空

我有一个设置,我想有一个方法来处理不同的报告模板(每个模板的字段比其他模板少/多),方法是传入报告名称,并在运行时创建对象。然后检查每个字段是否存在,如果存在,则设置值。然后,该对象将被序列化为JSON以返回

我有一个测试设置如下。问题是我无法获得所创建对象的字段列表。物体。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));
    }
}

型号:

CustomerReservationReport

这是父类,所有基本报告字段都在这里

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());
    }
}

CustomerReservationReportBasic

这将是各种各样的报告之一

public class CustomerReservationReportBasic extends CustomerReservationReport {
    public CustomerReservationReportBasic() {
        super();
    }
}

共 (1) 个答案

  1. # 1 楼答案

    来自Javadoc的Class::getDeclaredFields()

    Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

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