samedi 28 mars 2020

How to cast instance by classname in Spring's validator interface realization

I have class - AbstractOrder - it have basic realization and fields. And also i have three another which extends AbstractOrder - EmployeeOrder, StudentOrder, PostgraduateOrder, but have additional field - id. I would like to create a single validation class for all 3 entities. Here is my code. So, my question is "how to create an object of instance of nessasary class and cast object to it using Reflection api". My entities doesn't have a constructors. I try to something like that:

@Service
public class TripOrderValidator implements Validator {

  @Autowired
    private TripOrderService tripOrderService;

    Class <?> typeOfOrder;

    @Override
    public boolean supports(Class<?> aClass) {

        if (AbstractTripOrder.class.isAssignableFrom(aClass)) {
            typeOfOrder = aClass;
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void validate(Object o, Errors errors) {

           Class<? extends AbstractTripOrder> tripOrder = (Class<? extends AbstractTripOrder>) typeOfOrder.cast(o);
//can't execute the method

//tripOrder.getNumber();
}

}

But i can't call the methods of the class. I want to use it like that. For example. In method support i have class EmployeeOrder. Then in validate method i create object and cast parameter o to that classType:

EmployeeOrder order = (EmployeeOrder) o;




Aucun commentaire:

Enregistrer un commentaire