简体   繁体   中英

<Java reflection> object.getClass().getDeclaredFields() is empty

I have a setup where I want to have a method to handle different report templates (each template have less/more fields than the others) by passing in the report name and create the object at runtime. It shall then check if each field exists, and set the value if it does. The object will then be serialized to JSON for return.

I have a test setup as below. The problem is that I cannot get a list of fields of the created object. The object.getClass().getDeclaredFields() always give an empty array.

Would like to see if you can spot out any mistakes or if there is smarter way of doing this.

Main logic:

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

Model:

CustomerReservationReport

This is the parent class and all the fundamental report fields are here

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

This would be one of the various kinds of reports.

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

From the Javadoc for 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 .

You will need to also get the fields of the object's superclass(es).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM