首页 > 解决方案 > intellij idea 结构搜索和替换 - 查找所有调用 api 的方法

问题描述

我正在尝试在调用特定静态 api 的大型 Java 项目中查找所有方法,然后为这些方法添加注释。

这些方法可以具有任意复杂性。它可以很简单MyAPI.method("foo");,但也可以try(Int result = MyAPI.AnotherMethod("foo")) { }。它可以嵌套在代码块内、lambda 表达式中、任何地方。

我能够创造的最好的是:

class $_1$ { 
  $ReturnType$ $Method$ /* count 1 to inf */ ($ParameterType$ $Parameter$ /* count 0 to inf */)
  {
    $stmt1$; /* count 0 to inf */
    MyAPI.$MethoddCall$($param$ /* count 0 to inf */);
    $stmt2$; /* count 0 to inf */
  }
}

这找到了一些用法,但通常只有最简单的一种。在下面的示例类中,它仅找到usage1 (a,b,c) 和usage5。其他示例略过。甚至可以编写这样的一般搜索,还是我需要针对所有可能的情况对其进行调整?

关键是,该 api 被用于数千种方法中,并且每个方法都必须进行注释,所以我正在寻找任何意味着我不必手动完成的方法。最坏的情况,我会用 awk 试试运气,但这会弄乱我们正在使用的疯狂 CVS,所以我更喜欢 Idea 解决方案。

现在举个例子:

import java.io.PrintWriter;

public class SearchAndReplaceTest
{
    private static class MyAPI
    {
        public static void foo(String x)
        {}

        public static  int bar(String x)
        {
            return 1;
        }

        public static  int baz(String x, int y)
        {
            return 1;
        }

        public static PrintWriter guu(String x)
        {
            return null;
        }
    }


    public void usage1a()
    {
        MyAPI.foo("aaaa");
    }

    public void usage1b()
    {
        MyAPI.baz("aaaa", 1+1);
    }

    public void usage1c()
    {
        MyAPI.baz("aaaa", (1+1)-1);
    }

    private static int usage2(String xxxx) throws Exception
    {
        new String();
        if(MyAPI.bar("x") == 1)
        {}
        return 0;
    }

    private void usage3a(String xxxx) throws Exception
    {
        new String();
        if(1 == 1)
        {
            MyAPI.baz("xxx", (10+3) - 1);
        }
    }

    private void usage3b(String xxxx) throws Exception
    {
        new String();
        if(1 == 1)
        {
            MyAPI.foo("xxx");
        }
    }

    private static void usage4(String xxxx) throws Exception
    {
        new String();
        try(PrintWriter x = MyAPI.guu("x"))
        {}
        catch (Exception e){}
    }

    public void usage5()
    {
        new String();
        MyAPI.foo("aaaa");
        if(1==0)
        {}
    }
}

标签: javaintellij-ideastructural-search

解决方案


我已经找到了如何做到这一点。与其试图利用结构搜索的力量,我只需要通过脚本来搜索函数体。所以搜索是:

class $_1$ { 
  $ReturnType$ $Method$ ($ParameterType$ $Parameter$);
}

有了这些限制:

$Parameter$ // count: [0, inf]
$Method$ // count: [1, inf], text: [x] within hierarchy, script: Method.getText().contains("MyAPI")

推荐阅读