如何使用JDT获取静态字段的所有引用 [英] How to get all the references of static field with JDT

查看:203
本文介绍了如何使用JDT获取静态字段的所有引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 Java:查找所有来电者方法 - 获取调用特定方法的所有方法,提供如何查找特定方法的所有调用者的提示。

I found Java: Find all callers of a method – get all methods that call a particular method that gives a hint on how to find all the callers of a specific method.

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

Then, how to get the users of a static field?

例如,当我在 AnotherClass z >,并使用 ClassA 访问,如何获取 IMethod ClassA#moved

For example, when I have static z in AnotherClass, and it is accessed with ClassA, how to get the 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是全功能的。在您的情况下,以下代码将足够:

The example is base on the org.eclipse.jdt.internal.* classes, I think you don't need to take so much effort to do this, since JDT SearchEngine API is full-featured. In your case, the following code will be enough:

    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
    }

这篇关于如何使用JDT获取静态字段的所有引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆