從eclipse中的界面快速創建類

[英]Quickly create class from an interface in eclipse


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這樣的標准名稱來生成它

5 个解决方案

#1


4  

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

#2


41  

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

除了以下方面之外沒有看到任何其他內容:右鍵單擊包瀏覽器中的接口類型,選擇New-> Class,它將自動實現該接口。您仍然必須自己命名新課程。

#3


7  

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.

重構應從類中提取所有(切換為“所有公共”)方法,創建接口並將舊類重命名為ClassnameImpl。

... 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.1 2003) for you to choose in order to automatically implement those public abstract methods.

...並作為功能請求輸入,在故障單9798中“已解決”,因為New-> Class將具有選項“Inherited abstract method”(至少自Eclipse SDK 2.1 2003)供您選擇以便自動實現那些公共抽象方法。

alt text

#4


3  

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或右clic,您就可以根據需要使用TODO,javadoc注釋等創建所有方法(具體取決於Eclipse的配置方式)。

#5


0  

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".

方法1:右鍵單擊類名,然后選擇“快速修復”,然后會出現一個小菜單,您可以在其中選擇:“添加未實現的方法”。

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

方法2:右鍵單擊類名,轉到“源”,然后選擇“覆蓋/實現方法”


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/09/06/7250f0de79458f96365e26aa274428b5.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com