How to get the reference of the selected class in Eclipse Package Explorer?

Asked

Viewed 997 times

3

I’m making a plugin and when I right click on a class of Package Explorer, my Handler could reference the clicked class.

When I right click on a class of Package explorer opens the menu, in this menu I created a new function (line), when I click on it it is treated in Handler which is a class, and in this Handler I would like to know how I get an instance(reference) of the class I right-clicked.

The Interface part is implemented in xml plugin.

  <?xml version="1.0" encoding="UTF-8"?>
  <?eclipse version="3.4"?>

  <plugin>
     <extension
           point="org.eclipse.ui.menus">
        <menuContribution
              allPopups="false"
              locationURI="popup:org.eclipse.jdt.ui.PackageExplorer">
           <command
                 commandId="br.usp.each.saeg.badua.dataflow.handler"
                 label="Dataflow Coverage"
                 style="push">
              <visibleWhen
                    checkEnabled="false">
                 <with
                       variable="activeMenuSelection">
                    <iterate
                          ifEmpty="false"
                          operator="or">
                       <adapt
                             type="org.eclipse.jdt.core.ICompilationUnit">
                       </adapt>
                    </iterate>
                 </with>
              </visibleWhen>
           </command>
        </menuContribution>
     </extension>


     <extension
           point="org.eclipse.ui.commands">
        <command
              defaultHandler="DataflowHandler"
              id="br.usp.each.saeg.badua.dataflow.handler"
              name="DataflowViewHandler">
        </command>
     </extension>

  </plugin>

and have the class Dataflowhandler.java that is the Handler

import org.eclipse.core.commands.Abstracthandler;

  import org.eclipse.core.commands.ExecutionEvent;
  import org.eclipse.core.commands.ExecutionException;
  import org.eclipse.ui.PlatformUI;


  public class DataflowHandler extends AbstractHandler {

     @Override
     public Object execute(ExecutionEvent event) throws ExecutionException {
             try {

             #codigo para conseguir a instancia da classe selecionada

             } catch (Exception e) {
                 e.printStackTrace();
             }
             return null;
     }
  }

Basically what I need is that when I click on this button I get a reference to the Main.java class, which is the class I right-clicked on.

Visualizacao

2 answers

2


Unfortunately, the possible variations make the code to get the selected class a bit complex. Your selection may contain one or several files, as well as more abstract concepts like "Project" or "Package" (which you discarded with the filter); Actually Main.java is just a file containing source code. Let’s call this (grossly) compilation unit (in a Java nature project). The problem is that a build unit may contain classes, interfaces, enums, etc.

Anyway, you can get the current selection with the following code:

// Obtem o workbench
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
// E o serviço de seleção
ISelectionService service = window.getSelectionService();
IStructuredSelection structured = (IStructuredSelection) service.getSelection();

// Pode ser um arquivo
if (structured.getFirstElement() instanceof IFile) {
    IFile file = (IFile) structured.getFirstElement();
    // Caminho do arquivo
    IPath path = file.getLocation();
    System.out.println(path.toPortableString());
}

// E pode ser uma unidade de compilação
if (structured.getFirstElement() instanceof ICompilationUnit) {
    ICompilationUnit cu = (ICompilationUnit) structured.getFirstElement();
    System.out.println(cu.getElementName());
}

// Para seleções múltiplas use structured.getIterator()

The interface Icompilationunit gives you ways to find out if the build unit contains classes.

For example:

if (cu.findPrimaryType().isClass()) {
    // Finalmente o premio
    String fullyQualifiedName = cu.findPrimaryType().getFullyQualifiedName();

Remembering that a single compilation unit can have several types besides the primary - you may be interested, for example, in other classes (non-public), interfaces, annotations or enums in the file body, as well as nested classes and types:

for (IType type : cu.getTypes()) {
    // Tipos do nível superior   
}

for (IType type : cu.getAllTypes()) {
    // Tipos do nível superior e tipos aninhados  
}

I strongly recommend the article Eclipse JDT - Abstract Syntax Tree (AST) and the Java Model - Tutorial teaching how to work with the various types of JDT - Projects, fragments, packages, compilation units, methods and fields).

Outside the scope of the question, but send a hug to the SAEG staff and to Professor Chaim :).

  • Thank you very much for the reply Anthony, as there was some time since I posted this doubt had already managed to work with these Icompilationunit, but the article can still be useful because I am not using AST. Hahaha can leave, I will. Abs!

0

If you have the class name, you create the instance with

Class.newInstance()

See on documentation.

  • I think you have confused which class I want to take, I want to take the instance of the class I right-clicked and not the instance of the class that takes care of the "click"

  • you better post your plugin code

  • Actually that would be the first thing I’d like to do, so I don’t have code, just the interface and Handler

  • you wrote "in this menu I created a new function (line), when I click it it is treated in Handler that is a class". You can post this code?

  • 1

    edited the question with the code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.