towi
towi

Reputation: 22267

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?

Upvotes: 7

Views: 3546

Answers (1)

digitaljoel
digitaljoel

Reputation: 26574

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

Upvotes: 8

Related Questions