validate constructor arguments or method parameters with annotations, and let them throw an exceptio
        Posted  
        
            by marius
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by marius
        
        
        
        Published on 2010-06-12T10:20:18Z
        Indexed on 
            2010/06/12
            10:22 UTC
        
        
        Read the original article
        Hit count: 319
        
I am validating constructor and method arguments, as I want to the software, especially the model part of it, to fail fast.
As a result, constructor code often looks like this
public MyModelClass(String arg1, String arg2, OtherModelClass otherModelInstance) {
    if(arg1 == null) {
        throw new IllegalArgumentsException("arg1 must not be null");
    }
    // further validation of constraints...
    // actual constructor code...
}
Is there a way to do that with an annotation driven approach? Something like:
public MyModelClass(@NotNull(raise=IllegalArgumentException.class, message="arg1 must not be null") String arg1, @NotNull(raise=IllegalArgumentException.class) String arg2, OtherModelClass otherModelInstance) {
    // actual constructor code...
}
In my eyes this would make the actual code a lot more readable.
In understand that there are annotations in order to support IDE validation (like the existing @NotNull annotation).
Thank you very much for your help.
© Stack Overflow or respective owner