2

我找到了 Java:查找方法的所有调用者——获取调用特定方法的所有方法,该方法提示如何查找特定方法的所有调用者。

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

例如,当我有 static zinAnotherClass并且使用 访问它时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;
    }
4

2 回答 2

4

该示例基于 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
    }
于 2013-01-24T09:20:21.247 回答
0

您需要使用 JDT Core SearchEngine API 来查找(引用)java 元素。

于 2013-01-24T06:10:22.337 回答