Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use an annotation inside a method body?

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

For example:

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");
    }
}

To abbreviate the often written (too often, definitly!):

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 embedded annotation possible at all? Or something similar?

like image 294
towi Avatar asked Jun 05 '13 20:06

towi


1 Answers

ElementType specifies the valid targets of an annotation. You can't annotate any old statement. It's basically narrowed down to declarations; declarations of:

  • annotation type
  • constructor
  • field
  • local variable
  • method
  • package
  • parameter
  • type
like image 188
digitaljoel Avatar answered Nov 20 '22 12:11

digitaljoel