gpt4 book ai didi

java - 查找仅使用特定类型参数的一个特定属性的所有 Java 方法

转载 作者:搜寻专家 更新时间:2023-11-01 03:45:47 52 4
gpt4 key购买 nike

我们正在尝试在所有地方识别特定类型的对象仅用于从中获取特定属性,并将该属性传递给方法。

我认为 IntelliJ IDEA 的“结构搜索”可能是一个很好的工具,但我不确定如何制定搜索模板。

一个具体的例子:

public class MyClass {
public Long getId() {...}
public void setSomethingElse(int se) {...}
}

public class SomeOtherClasses {
public void shouldBeMatched(MyClass mc) {
doSomething();
mc.getId();
doSomethingElse();
}

public void shouldNotBeMatched(MyClass mc) {
doSomething();
mc.getId();
mc.setSomethingElse(14);
doSomethingElse();
}

public void alsoShouldNotBeMatched(MyClass mc) {
shouldBeMatched(mc);
}
}

在上面的例子中,如果我正在寻找只使用 getId 的方法,那么我应该找到 shouldBeMatched,而不是 shoudNotBeMatchedalsoShouldNotBeMatched,因为除了调用 getId() 之外,它们还对 mc 对象做了一些事情。

最佳答案

I'm thinking IntelliJ IDEA's "Structural Search" might be a good tool for this

确实如此。不过,文档可能很难。

让我们检查一下 Search templates, filters, and script constraints页。它进行如下。

Let's say, you have a variable that matches a method, a toString() method. Then this variable is actually a PsiMethod node. Retrieving variable.parent will produce a PsiClass node, and so forth. variable.text then will give you the entire text of the method. If you just need the name of the method, you can use variable.name.

看来只要选择合适的模板,编写相应的Groovy脚本就可以完成任务。

该模板称为类的方法,可以在现有模板 下找到。它们提供 __context__变量以用于脚本。

我们必须确保匹配的方法有参数。这很简单,只需在 $Parameter$ 变量上放置一个计数过滤器即可。

Count filter

然后我们需要提取所需类型的参数名称,并查看它是否在方法体中被调用。下面的脚本就可以了。

def parameters = __context__.getParameterList().getParameters();
def parameter = parameters.find { p -> p.getType().getName().equals('MyClass') };
if (parameter == null) return false;
String parameterName = parameter.getName();
String methodText = __context__.getText();
String occurrence = "${parameterName}.";
String methodCall = "${parameterName}.getId()";
return methodText.count(occurrence) > 0 && methodText.count(occurrence) == methodText.count(methodCall);

将其放入$Method$变量过滤器并验证结果。

Verify results by pressing Find

关于java - 查找仅使用特定类型参数的一个特定属性的所有 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56691174/

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com