mardi 15 décembre 2020

Hi I have the following test setup in which I am trying to check if a field exists, and set the value if it does.

In the step when it tries to set the value of the found field (i.e. field.set(cls, "Peter")), an exception is thrown

java.lang.IllegalArgumentException: Can not set java.lang.String field CustomerReservationReport.name to java.lang.Class

May I seek for you advice for the cause and resolution? Thank you.

Main logic:

import java.lang.reflect.Field;
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, NoSuchFieldException {
        Class<?> cls = Class.forName("CustomerReservationReportBasic");
        CustomerReservationReport customerReservationReport = (CustomerReservationReport) cls.getDeclaredConstructor()
                .newInstance();
        if (hasField(customerReservationReport, "name")) {
            Field field = cls.getSuperclass().getDeclaredField("name");
            field.setAccessible(true);
            field.set(cls, "Peter");
            System.out.println(customerReservationReport.getName());
        }
    }

    private static boolean hasField(Object object, String fieldName) {
        boolean isFoundInCurrentClass = Arrays.stream(object.getClass().getDeclaredFields())
                .anyMatch(f -> f.getName().equals(fieldName));
        boolean isFoundInParentClass = Arrays.stream(object.getClass().getSuperclass().getDeclaredFields())
                .anyMatch(f -> f.getName().equals(fieldName));
        return isFoundInCurrentClass || isFoundInParentClass;
    }
}

Models:

CustomerReservationReport

This is the parent class

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 is the child class

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




Aucun commentaire:

Enregistrer un commentaire