I have a class A
(listed below) which can have many different types of attributes saved to it. Naturally these attributes can be of different types. Based on the type of attribute I want to apply some validations to it.
What would be the best way of doing it in Micronaut?
Here is an example of what I want to achieve:
public class A {
private String type;
private String value;
// getter/setter omitted…
}
Some example instances of class A:
{type: "type1", value: "examplevalue1"}
{type: "type2", value: "examplevalue2"}
{type: "type2", value: "examplevalue3"}
Then I have some set of validation rules which are relevant to the respective types. Each type (type1
, type2
, type3
) have separate set of validation rules. These rules are not just restricted to String validation but also semantic and business validation.
CodePudding user response:
I would solve this using specific class per type. You can introduce an interface A
interface A {
String getType();
}
and then implement the concrete types.
public class Type1 implements A {
@NotBlank
private String value;
@Override
public String getValue() { return this.value; }
public void setValue(String v) { this.value = v; }
}
public class Type2 implements A {
@YourCustomValidator
private String value;
@Override
public String getValue() { return this.value; }
public void setValue(String v) { this.value = v; }
}
and then implement a custom Jackson Deserializer which is able to build an instance of A
by inspecting the JSON string field type
.
I don't think that Drools has anything to do with this question.