简体   繁体   中英

Can I use an annotation inside a method body?

Allows the semantics of Java annotations to place them somewhere inside a functions body , eg 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM