I want to write my own validator and code generator for my beans. I define annotations and annotate my fields with them. When I validate them:
public boolean validate(Object obj) {
Class clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
for (Annotation annotation : field.getAnnotations()) {
...//What to do here
}
}
return false;
}
i.e. my annotation is @NotEmpty
Should I go like if else if else ... or is there any other short way for it(and what to use to compare is that the annotation that I look i.e. @NotNull -> with annotation.equals(“NotNull”))? I mean how it can be implemented. On the other hand project Lombok has an annotation like that:
@Getter @Setter
How to generate getter and setters dynamically (or before compiling) for my classes(I want to implement it just with Java without any other libraries)?
I think you’d better search for the annotations you need rather that looping through all annotations. You can see if a annotation is present like this:
And to get the annotation and check it’s elements you can use:
To modify your classes at runtime I think this is what you’re looking for. Here you can find a tutorial for ASM.