简体   繁体   中英

How can I achieve bean validation in Java SE 1.6

The project which I work is a simple Java SE program which is ran using public static void main method. I have a DTO bean called StudentBean:

class StudentBean {
    private String firstname;
    private String lastname;
    private Integer id;
    private Integer age;
    //setters and getters
}

I have over 100k student beans stored in a java.util.ArrayList . We have set of rules for each field. For ex, firstname should not be null and empty, age cannot be negative.

How do I write java code for validating hundreds of thousands of beans against the rules we have and write the log for the beans which violates the rules?

We thought of writing custom annotations like @NotNull, @NotEmpty, @PositiveNumber and have a validator logic which validates the beans according to the annotations they have on their variables. If you find this good, please point me to online resources which I can use to implement this.

As this is Java SE project, we do not have javax.validation jar, so no scope of using this library. It would be very helpful if we can achieve it using Java SE library only.

You can have a look at hibernate validator, and how to bootstrap the validation. There are already constraints you need available out of the box. The fact that this is Java SE project doesn't mean you can't bootstrap validation by yourself.

I would try to keep it simple and just use a method public boolean isValid () within the bean which implement your rules. This way you need no annotations and no reflection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM