从eclipse中的界面快速创建类

lau*_*rie 31 java eclipse

是否有一个eclipse插件允许我从界面快速生成一个新类?

而不是必须在新类对话框中键入

理想情况下,让我选择像Impl这样的标准名称来生成它

nos*_*nos 43

除了以下方面之外没有看到任何其他内容:右键单击包浏览器中的接口类型,选择New-> Class,它将自动实现该接口.您仍然必须自己命名新课程.

  • @ user710818您可能右键单击Package Explorer中的.java文件,而不是类型(即只展开包含该界面的.java文件,右键单击界面类型,选择New-> Class).这至少在Indigo和Helios中完美无缺. (35认同)
  • @nos谢谢,它也在Luna工作 (2认同)

Von*_*onC 7

它实际上是在2002年被问到的

重构应从类中提取所有(切换为"所有公共")方法,创建接口并将旧类重命名为Classname Impl.

...并作为功能请求输入,在故障单9798中 "已解决" ,因为New-> Class将具有选项"Inherited abstract method"(至少自Eclipse SDK 2.1 2003)供您选择以便自动实现那些公共抽象方法.

替代文字

  • 我想看到的是New Class对话框,它在"implements"列表中预先填充了我选择的界面. (2认同)

Ric*_*ler 5

我还没有看到任何插件可以做到这一点,但这对我来说似乎是一个合理的捷径。

以下内容可以构成插件直接从所选接口生成类的基础。它适用于我的盒子(TM)。

它目前假设该类将采用后缀为“Impl”的接口名称,如果该类型已经存在,则失败(记录原因)。

我能想到的一些改进:

  • 允许选择多个接口
  • 为实现后缀和包名定义首选项页面
  • 如果“默认”实现已经存在,则打开一个带有填充值的对话

该插件为编辑器、视图和文本选择的上下文菜单添加了一个命令,如果选择未解析为界面,则禁用该项目。它也可以激活ctrl-6(您显然可以更改 plugin.xml 中的键绑定以适应您的心情)。

插件代码如下:

package name.seller.rich.classwizard.actions;

import java.util.Collections;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.expressions.EvaluationContext;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.ui.wizards.NewClassWizardPage;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;

public class GenerateClassHandler extends AbstractHandler {

    public GenerateClassHandler() {
    }

    public Object execute(ExecutionEvent event) throws ExecutionException {
        NewClassWizardPage page = new NewClassWizardPage();

        EvaluationContext evaluationContext = (EvaluationContext) event
                .getApplicationContext();

        IWorkbenchPart activePart = (IWorkbenchPart) evaluationContext
                .getVariable("activePart");
        try {
            IStructuredSelection selection = SelectionConverter
                    .getStructuredSelection(activePart);

            IType type = getFirstType(selection);

            if (type != null && type.exists() && type.isInterface()) {
                page.init(selection);

                String typeName = type.getElementName() + "Impl";
                // TODO handle existing type
                page.setTypeName(typeName, true);

                // generate constructors and methods, allow modification
                page.setMethodStubSelection(false, true, true, true);

                page.setSuperInterfaces(Collections.singletonList(type
                        .getFullyQualifiedName()), true);
                try {
                    page.createType(new NullProgressMonitor());

                    IResource resource = page.getModifiedResource();
                    if (resource != null) {
                        IWorkbenchWindow window = HandlerUtil
                                .getActiveWorkbenchWindowChecked(event);
                        BasicNewResourceWizard
                                .selectAndReveal(resource, window);
                        openResource((IFile) resource, window);
                    }
                } catch (CoreException e) {
                    // TODO if we get this the type already exists, open a
                    // dialogue to allow the type name to be modified or give
                    // up?
                    logException(e);
                }

            }
        } catch (JavaModelException e) {
            logException(e);
        } catch (InterruptedException e) {
            logException(e);
        }
        return null;
    }

    protected void openResource(final IFile resource, 
            IWorkbenchWindow window) {
        final IWorkbenchPage activePage = window.getActivePage();
        if (activePage != null) {
            final Display display = window.getShell().getDisplay();
            if (display != null) {
                display.asyncExec(new Runnable() {
                    public void run() {
                        try {
                            IDE.openEditor(activePage, resource, true);
                        } catch (PartInitException e) {
                            logException(e);
                        }
                    }
                });
            }
        }
    }

    @Override
    public void setEnabled(Object context) {
        if (context != null && context instanceof EvaluationContext) {
            EvaluationContext evaluationContext = (EvaluationContext) context;

            IWorkbenchPart activePart = (IWorkbenchPart) evaluationContext
                    .getVariable("activePart");

            try {
                IStructuredSelection selection = SelectionConverter
                        .getStructuredSelection(activePart);

                IType type = getFirstType(selection);

                if (type != null) {
                    setBaseEnabled(type.isInterface());
                    return;
                }
            } catch (JavaModelException e) {
                logException(e);
            }
        }

        setBaseEnabled(false);
    }

    private IType getFirstType(IStructuredSelection selection) {
        IJavaElement[] elements = SelectionConverter.getElements(selection);

        if (elements != null && elements.length > 0) {
            if (elements[0] != null && elements[0] instanceof IType) {
                return (IType) elements[0];
            }

            try {
                if (elements[0] != null
                        && elements[0] instanceof ICompilationUnit) {
                    IType[] types = ((ICompilationUnit) elements[0])
                            .getAllTypes();

                    if (types != null && types.length > 0) {
                        return types[0];
                    }
                }
            } catch (JavaModelException e) {
                logException(e);
            }
        }
        return null;
    }

    protected void logException(Exception e) {
        JavaPlugin.log(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

贡献命令的 plugin.xml 是:

<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>
<plugin>
   <extension
     point="org.eclipse.ui.commands">
      <command
        name="Generate Class"
        categoryId="name.seller.rich.classwizard.category"
        id="name.seller.rich.classwizard.generateClassCommand">
      </command>
   </extension>
   <extension
     point="org.eclipse.ui.handlers">
      <handler
        commandId="name.seller.rich.classwizard.generateClassCommand"
        class="name.seller.rich.classwizard.actions.GenerateClassHandler">
      </handler>
   </extension>
   <extension
     point="org.eclipse.ui.bindings">
      <key
        commandId="name.seller.rich.classwizard.generateClassCommand"
        contextId="org.eclipse.ui.contexts.window"
        sequence="M1+6"
        schemeId="org.eclipse.ui.defaultAcceleratorConfiguration">
      </key>
   </extension>
   <extension
     point="org.eclipse.ui.menus">
      <menuContribution
        locationURI="popup:org.eclipse.ui.popup.any?after=additions">
     <command
           commandId="name.seller.rich.classwizard.generateClassCommand"
           mnemonic="G">
     </command>
      </menuContribution>
   </extension>
</plugin>
Run Code Online (Sandbox Code Playgroud)

和 manifest.mf 看起来像这样:

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Classwizard
Bundle-SymbolicName: name.seller.rich.classwizard; singleton:=true
Bundle-Version: 1.0.0
Require-Bundle: org.eclipse.ui,
 org.eclipse.core.runtime,
 org.eclipse.jdt.core;bundle-version="3.5.0",
 org.eclipse.core.expressions;bundle-version="3.4.100",
 org.eclipse.jface.text;bundle-version="3.5.0",
 org.eclipse.jdt.ui;bundle-version="3.5.0",
 org.eclipse.ui.ide;bundle-version="3.5.0",
 org.eclipse.ui.editors;bundle-version="3.5.0",
 org.eclipse.core.resources;bundle-version="3.5.0"
Eclipse-AutoStart: true
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Run Code Online (Sandbox Code Playgroud)