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

时间:2013-01-24 03:47:54

标签: java eclipse eclipse-jdt

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

然后,如何获取静态字段的用户?

例如,如果我在z中有静态AnotherClass,并且使用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;
    }

2 个答案:

答案 0 :(得分: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
    }

答案 1 :(得分:0)

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