mardi 24 novembre 2020

How to create an object just using class name in java with spring validator?

Im making spring validation and would like to make an generic validation for three similar entities: StudentOrder, EmployeeOrder, TeacherOrder. All that have the same fields. But its a different entities. The idea is to create a one validator for three entities.

Now i have this working on only one entity EmployeeOrder:

@Service
public class EmployeeOrderValidator implements Validator {

    @Autowired
    private OrderService OrderService;

    Class <?> typeOfOrder;

    @Override
    public boolean supports(Class<?> aClass) {
        typeOfOrder=aClass;
        return aClass.isInstance(EmployeeOrder.class);
    }

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

  EmployeeOrder tripOrder = ((EmployeeOrder) o);
//making constraints  

}

}

So i would like to have something like that for all three Entities:

@Service
    public class EmployeeOrderValidator implements Validator {
    
        @Autowired
        private OrderService OrderService;
    
        Class <?> typeOfOrder;
    
        @Override
        public boolean supports(Class<?> aClass) {
            typeOfOrder=aClass;
            return aClass.isInstance(EmployeeOrder.class);
        }
    @Override
            public void validate(Object o, Errors errors) {
        //EmployeeOrder,StudentOrder or TeacherOrder will create
    
          typeOfOrder order = ((typeOfOrder) o);
    
        //making constraints  
        
        }
    

To create an object depends on giving type of aClass will create an instance with cast of this type.





Aucun commentaire:

Enregistrer un commentaire