Java 在eclipse中从接口快速创建类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1386294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:29:18  来源:igfitidea点击:

Quickly create class from an interface in eclipse

javaeclipse

提问by laurie

Is there a plugin for eclipse which allows me to quickly generate a new class from an interface?

是否有 Eclipse 插件可以让我从接口快速生成一个新类?

Rather than having to do the typing in the new class dialog

而不是必须在新的类对话框中打字

Ideally letting me choose a standard name like Impl for it to generate

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

采纳答案by Rich Seller

I've not seen any plugins that do this, but it seems a reasonable shortcut to me.

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

The following could form the basis for a plugin to generate a class directly from a selected interface. It works on my box(TM).

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

It currently assumes the class will take the interface name suffixed with "Impl" and fails (logging the reason) if that type already exists.

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

Some enhancements I can think of:

我能想到的一些改进:

  • allow selection of multiple interfaces
  • define a preference page for the implementation suffix and package name
  • open a dialogue with the values populated if the "default" implementation already exists
  • 允许选择多个接口
  • 为实现后缀和包名定义首选项页面
  • 如果“默认”实现已经存在,则打开一个带有填充值的对话

The plugin adds a command to the context menu for editors, views and text selections, disabling the item if the selection doesn't resolve to an interface. It can also be activated with ctrl-6(you can obviously change the key-bindings in the plugin.xml to suit your mood).

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

The plugin code is as follows:

插件代码如下:

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);
    }
}

The plugin.xml to contribute the command is:

贡献命令的 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>

and the manifest.mf looks like this:

和 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

回答by nos

Havn't seen anything other than: right click the interface type in the package explorer, chose New->Classand it will automatically implement that interface. You still have to name the new class yourself.

除了:右键单击包资源管理器中的接口类型,选择New->Class,它会自动实现该接口。您仍然需要自己命名新类。

回答by VonC

It was actually asked as soon as 2002

其实早在2002年就有人问了

The refactoring should extract all (switch for "all public") methods from a class, create an interface and rename the old class to ClassnameImpl.

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

... and entered as a feature request, "resolved "in ticket 9798, because the New->Class will have the option "Inherited abstract method" (since at least Eclipse SDK 2.12003) for you to choose in order to automatically implement those public abstract methods.

...并作为功能请求输入,“已解决”在票证 9798 中,因为 New->Class 将有选项“继承的抽象方法”(至少从Eclipse SDK 2.12003 起)供您选择以便自动实现那些公共抽象方法。

alt text

替代文字

回答by KLE

If you create a class, let it implement an interface.

如果你创建一个类,让它实现一个接口。

You get errors, because the methods are not defined. Just Ctrl-1, or right clic, and you can create all methods, with TODOs, javadoc comments and so on as needed (depending on the way your Eclipse is configured).

你会得到错误,因为方法没有定义。只需按 Ctrl-1 或右键单击,您就可以根据需要使用 TODO、javadoc 注释等创建所有方法(取决于 Eclipse 的配置方式)。

回答by The Quantum Physicist

Method 1: Right click on the class name, then choose "Quick Fix", and then a small menu will appear, within which you choose: "Add unimplemented methods".

方法一:右击类名,选择“快速修复”,会出现一个小菜单,在里面选择:“添加未实现的方法”。

Method 2: Right click on the class name, go to "Source", then choose "Override/Implement Methods"

方法二:在类名上右击,进入“Source”,然后选择“Override/Implement Methods”