Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When developing an Eclipse plugin, how to get access to the project's Java Model and AST root node?

I am currently developing a plugin that'll make use of Eclipse's Java Model and Eclipse's Java Abstract Syntax Tree.

So what I am looking for is a way of getting though my plugin the Java Model root object and the current Java project's AST Root node:

public class SampleHandler extends AbstractHandler {
    public Object execute(ExecutionEvent event) throws ExecutionException {     
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
                ??? how to get the current Java project Java Model? and the AST node?
        }
}

Thanks

like image 287
devoured elysium Avatar asked Dec 22 '22 15:12

devoured elysium


2 Answers

I use the following to get the model:

public static IJavaModel prepareWorkspace() {
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot workspaceRoot = workspace.getRoot();
    IJavaModel javaModel = JavaCore.create(workspaceRoot);
    return javaModel;
}

You can find this and some other helpful Eclipse utility methods in EclipseUtils.java and EclipseSearchUtils.java.

like image 159
kc2001 Avatar answered May 12 '23 05:05

kc2001


You can get the selection from within your handler, and then you can decide what to do with it:

ISelection sel = HandlerUtil.getCurrentSelection(event);
if (sel instanceof IStructuredSelection) {
    // check to see if it's empty first, though
    Object obj = ((IStructuredSelection)sel).getFirstElement();
    // then have a look and see what your selection is.
}

If you have an IJavaElement, you can walk about the model until you find the point you are looking for. If you have an IFile/IResource, you can use some of the JavaCore methods to get to the java model.

like image 30
Paul Webster Avatar answered May 12 '23 05:05

Paul Webster