Intellij/ Java - identify calls to annotated methods

旧时模样 提交于 2019-12-13 04:46:10

问题


I need to be able to identify calls to methods with specific annotations in Intellij Idea 13, during compile time or by using static code analysis, like calls to @Deprecated methods are identified.

I have looked into doing a structural search in idea, these are supported in static code analysis, and am able to identify method calls from there, but I can't find a way to limit these to calls to method with annotations.

For example

public class A {
  @Foo
  public void foo(){
    // do something... 
  }

  public void bar() {
    // do something else.... 
  }

}

public class main {
  public static void main(String... args){
    A a = new A();

    a.foo(); // <---- should be highlighted
    a.bar();
  }
}

回答1:


You could do this in IDEA (which would involve using IDEA's internal interfaces; I don't know offhand which ones give access to annotations).

Depending on your use case, another alternative would be to use an external tool such as the Checker Framework. The advantage is that it is externally supported and has a lot of existing functionality, so there would be less of your own code to write and maintain. Additionally, other people who don't use IDEA would be able to run the analysis. The disadvantage is that there would be less tight integration with the IDE; you would need to configure IDEA to run the analysis, which is straightforward.




回答2:


You can by defining your own structural search template like this:

@Foo
$ReturnType$ $Method$($ParameterType$ $Parameter$);

save it e.g. as "methods annotated with @Foo"

and then do a structural search for $expression$ with the filter reference=methods annotated with @Foo
(to add filter to $Expression$ hover with the mouse over it and then there will be a popup asking you if you want to edit filters and then you add a reference filter)



来源:https://stackoverflow.com/questions/26213727/intellij-java-identify-calls-to-annotated-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!