I would like to get rid of NullPointerException and other errors using annotations for example there is a class

class A{ public List<@NonNull String> list = new ArrayList();//здесь надо запретить чтобы в коллекцию попадали null значения public Long compute(@Positive Integer num){//здесь разрешить только положит числа // calculation ... return num; } 

create your annotations

 @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE_PARAMETER}) public @interface NonNull {} @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.PARAMETER }) public @interface Positive{} 

ok now in the code i use this class

 A a = new A(); String test = null; Integer random = new Random().nextInt(); if ( random < 0 ){ a.compute(random); a.list.add(test); } else{ test = "NonNull"; a.list.add(test); } 

I understand how using Reflection you can scan class A before initialization and find these annotations in it, but it is not clear what to do next how you can install the check already in the working code ????

  • I see, @NonNull needs to be applied not to the type parameter, but to the arguments of the function - the analog of the .add () .addAll () or constructor. And with the compute method, it’s not quite clear what you want to achieve with annotations, because you can also check inside the method: if (num.compareTo(0) <= 0) throw new IllegalArgumentException() - Roman Bortnikov

1 answer 1

Using annotations, data can be validated by two completely different approaches:

  1. In the first case, annotations serve as hints for code analyzers. They can prompt and show places where there is a clear violation of restrictions. For more information, see the checker framework.
  2. The second approach allows validating data in runtime mode using a third-party framework. An example of this is the Hibernate Validator.

In both cases, you only need to set up annotations. Implementation of checks is carried out by a third-party tool.