0

I am learning Java annotations and I want to design a annotation like @NotNull which enforces compiler to throw an error on following:

@NotNull
private String myVar = null;

Now, I am not getting any lead in what to write in the body of the annotation:

@interface NotNull{
    // what goes here
}

Can I design such a functionality using Annotations or I have read it all wrong? I am looking at the checker package and it contains one such annotation.

Rajat Saxena
  • 3,834
  • 5
  • 45
  • 63
  • You can use [Bean validation](https://jcp.org/en/jsr/detail?id=303) otherwise you have to implement annotation processor. See [this answer](http://stackoverflow.com/questions/38185237/notnull-and-nullable-contradicting-java-annotations/38186011#38186011), it has some explanation on annotations – Vladimir Vagaytsev Jul 14 '16 at 07:43
  • 1
    You may want to look into Design by Contract, although it won't cause the compiler to fail, if you run your code through a checker, it will confirm the contracts have never been broken that you have specified. [Read more on this question](http://stackoverflow.com/questions/1075719/a-good-design-by-contract-library-for-java) – Draken Jul 14 '16 at 07:44

1 Answers1

3

You can only define the "meta" properties themselves in annotations, no actual logic

For compile-time annotation logic you need to write an annotation-processor (regular java-code that gets executed during compilation and allows you to examine annotated elements using reflection), during runtime you can use the regular reflection API

nihab
  • 56
  • 4