1

I'd like to create an annotation which effectively acts exactly as javax.annotation.Nullable. The reason I need this is that I just need a different name for it in my context.

The problem is that I have a field that has to acts as Nullable for the AutoValue so that it doesn't autogenerate the code for throwing exception if the value is null. And at the same time, I need the value to be NotNull for the JSR-303 validation.

In simple terms, I want to be able to build my object to invalid state, and then pass it to the validator that will do something about it. I want to have all validation handled by Hibernate Validator API that will generate violation constraints without crashing my program with the exception.

So I found out that the following will do what I want.

public abstract @Nullable @NotNull @Size(min = 3, max = 20) String getBane();

This will cause AutoValue to not throw exception if the value is not there, but Hibernate Validator will still validate that it should not be null. The only problem here is the word "Nullable", I'd like to call it "AutoValueNullable".

How would I "reinvent" the Nullable, or is there an open source code of it?

wesleyy
  • 2,575
  • 9
  • 34
  • 54
  • 1
    you can create your own validationannotations, but you'll have to provide the validation-handling for them as well yourself – Stultuske Dec 21 '17 at 13:44
  • @Stultuske I know that, but really have no idea how to do that. Is there some example on how to achieve what Nullable does (or their source code along with the validator)? That would help – wesleyy Dec 21 '17 at 13:51
  • there are tons of examples on the net: http://www.summa.com/blog/2013/05/30/creating-custom-validation-constraints – Stultuske Dec 21 '17 at 13:53
  • [The specification itself](http://beanvalidation.org/1.1/spec/) has [examples](http://beanvalidation.org/1.1/spec/#d0e670). – VGR Dec 21 '17 at 16:17

1 Answers1

0

Try to use jetbrain's @Contract annotation

@org.jetbrains.annotations.Contract("null->false")
public static boolean isDigits(@Nullable String str) {
boolean result = false;
//TODO: ...method implementation
return result;
}
Micah
  • 92
  • 10