1

On the one hand there is @NonNull, for which Oracle says "The compiler can determine cases where a code path might receive a null value, without ever having to debug a NullPointerException.". So, I suppose it is processed at compile time.

On the other hand there is @Inject, which injects constructors, methods and fields regardless of their access modifiers. So, I suppose they are processed at runtime.

One more thing that confuses me is that the fields can be injected at runtime even though they are private. Does it mean that the fields that have @Inject must have setter?

gicig
  • 334
  • 3
  • 14

1 Answers1

4

It entirely depends on the runtime retention policy of the annotation.

The @Inject annotation for instance has a retention policy of RUNTIME; which means that running code can inspect such annotations and act upon them (here by "injecting" values, as the name suggests).

I don't know specifically about @NonNull, but it probably works the same as @Nonnull from JSR 305 which has a retention policy of CLASS. It is used in tools such as FindBugs to perform bytecode analysis, for instance, and produce warnings where a misuse of a thusly annotated element is detected.

Finally, @Override is an example of an annotation with a SOURCE retention policy and the compiler can use it to determine that the code misuses the annotation and raise a compilation failure.

fge
  • 119,121
  • 33
  • 254
  • 329
  • And for the question regarding accessing private fields I found the answer [here](http://stackoverflow.com/questions/1196192/how-do-i-read-a-private-field-in-java). Thanks. – gicig Aug 24 '16 at 08:10