gpt4 book ai didi

java - 如何用JDT获取静态字段的所有引用

转载 作者:行者123 更新时间:2023-11-30 07:19:40 26 4
gpt4 key购买 nike

我找到了 Java: Find all callers of a method – get all methods that call a particular method这给出了如何找到特定方法的所有调用者的提示。

那么,如何获取静态字段的用户呢?

例如,当我在AnotherClass 中有静态z,并且它是通过ClassA 访问时,如何获取IMethod ClassA#moved?

public class AnotherClass {
public static int z = 20;
....
}


public class ClassA {
public int moved(int x, int y)
{
int temp = AnotherClass.z;
}

最佳答案

该示例基于 org.eclipse.jdt.internal.* 类,我认为您不需要为此付出太多努力,因为 JDT SearchEngine API 是全功能的。对于您的情况,以下代码就足够了:

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IProject plainProject = root.getProject("some project");
IJavaProject javaProject = JavaCore.create(plainProject);
try {
IType type = javaProject.findType("foo.bar.AnotherClass");
IField field = type.getField("z");
//IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { plainProject });
SearchPattern searchParttern = SearchPattern.createPattern(field,
IJavaSearchConstants.REFERENCES);
SearchRequestor requestor = new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match) {
System.out.println(match.getElement());
}
};
SearchEngine searchEngine = new SearchEngine();
searchEngine.search(searchParttern,
new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
requestor, new NullProgressMonitor());
} catch (Exception e) {
// some exception handling you need to do
}

关于java - 如何用JDT获取静态字段的所有引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14493613/

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