Can I use annotation inside the method body?

Allows the semantics of Java annotations to place them somewhere inside the body of functions , for example. annotate a specific function call, statement, or expression?

For instance:

class MyClass { void theFunc(Thing thing) { String s = null; @Catching(NullPointerException) //<< annotation ? s = thing.getProp().getSub().getElem().getItem(); if(s==null) System.out.println("null, you fool"); } } 

Shorten the often written (too often, definitely!):

 class MyClass { void theFunc(Thing thing) { String s = null; try { s = thing.getProp().getSub().getElem().getItem(); } catch(NullPointerException ex) { } if(s==null) System.out.println("null, you fool"); } } 

If the concept of this inline annotation is even possible? Or something similar?

+6
source share
1 answer

ElementType indicates the actual purpose of the annotation. You cannot annotate any old expression. It essentially boiled down to declarations; ads:

  • annotation type
  • Constructor
  • field
  • Local variable
  • method
  • package
  • parameter
  • of type
+7
source

Source: https://habr.com/ru/post/946620/


All Articles