Validate with object annotations within a method

2

I have a JavaBean with several attributes, and they need to be validated. It has an attribute of type enum, and according to the value of this attribute, the object needs some specific validations, and there are validations that are independent of the enum value.

I found an answer to another very interesting question (link: #), where the enum itself returns a validator. And I was thinking that this would be the best option.

So basically there's a JavaBean, which has an enum attribute. The enum has a getValidator method that returns a validator object that implements a Validator interface.

But in the end, the validations would happen in the .validate method of the Validator implementation:

public class CeletistaValidator implements FuncionarioValidator {
@Override
public void validate(Funcionario f) throws Exception {
    System.out.println(f.getNome() + " -> " + getClass().getName());
}}

But from what I could understand, in this case I will have to do the validations inside this validate () method and using methods. I would like to do the validations using annotations.

I thought of creating one more JavaBean for each type of employee, and in that new JavaBean put the annotations, but so it would get too many classes and confusing and seems not to be a good option.

Then illustrating my problem differently. Suppose I have an Employee class, and there is the EmployeeType attribute, which is an enum with the values collector, permanent frame, surfer. If you are a surfer, there will be more specific validations for the contact attributes such as email and phone, if it is a bookstore there are specific validations of name and documents, but all follow standard address validations. I would like to find a way to implement validations with annotations in this case, or if the solution I thought is acceptable.

    
asked by anonymous 26.07.2016 / 23:21

1 answer

1

IMHO, what you're doing is reinventing the wheel. In an object-oriented language, assuming you are using some persistence model, it seems to me more correct to create an Employee class and its specializations, eg:

public class Funcionario implements Serializable {
    private Integer id;
    private String nome;
    // Validações referentes aos campos de funcionários
}

And Surfer class, for example:

public class Surfista extends Funcionario implements Serializable { // Relacionamento um-para-um
    private Double tamanhoDaOnda;
    // Validações referentes aos campos de surfistas
}

Depending on the project, it is worth taking a look at the Hibernate Validator ( link ) and the JSF 2.2 validation scheme (<

    

27.07.2016 / 18:38