Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can @NonNull annotations finally be used in java 8 on runtime?

I am aware that there are loads of topics about @NonNull annotations already, however most of them are dated now Java 8 is there, meaning the API does not change anymore.

This question is further justified by the fact that Annotations on Types are now part of Java 8.

So I would want the following code:

public BaseChecker(final @NonNull File directory, final @NonNull Consumer<File> fileConsumer) {
    this.directory = directory;
    this.fileConsumer = fileConsumer;
}

I have two questions:

  1. Is this kind of syntax possible, at all?
  2. Does @NonNull finally work on runtime?

With working on runtime I mean:

  • If annotated on Object value, then it should throw a NullPointerException if and only if value == null.
  • This behaviour is similar to Objects.requireNonNull(value).
like image 525
skiwi Avatar asked May 07 '26 11:05

skiwi


1 Answers

Yes this syntax is possible. but no it doesnt "work" in the way you suggest. annotations are not supposed to "work" at all, they are decorations that can be inspected.

However it would be trivial to implement this type of behavior with AOP. check out AspectJ.

like image 187
aepurniet Avatar answered May 10 '26 01:05

aepurniet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!