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

3

I am making a plugin and when I right click on a Package Explorer class, my handler would get the class reference clicked.

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

The interface part is implemented in plugin.xml

  <?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>

I have a class DataflowHandler.java that is 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 this button I get a reference to the Main.java class, which is the class I clicked with the right mouse button.

    
asked by anonymous 31.01.2014 / 19:53

2 answers

2

Unfortunately, the possible variations make the code to get the selected class somewhat complex. Your selection may contain one or more 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 (roughly) a compilation unit (in a Java-like project). The problem is that a compilation unit can 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 compilation unit contains classes.

For example:

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

Remembering that a single build unit can have many types besides the primary - you may be interested 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 Eclipse JDT - Abstract Syntax Tree (AST) and the Java Model - Tutorial classes that teach how to work with the various types of JDT - Projects, fragments, packages, compilation units, methods and fields).

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

    
05.03.2014 / 20:17
0

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

Class.newInstance()

See the documentation .

    
02.02.2014 / 15:52