Java 在 Eclipse 中重命名包

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1355818/
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:05:18  来源:igfitidea点击:

Renaming packages in Eclipse

javaeclipserefactoring

提问by digiarnie

In Eclipse's "Package Explorer", let's say I have a list of packages like this:

在 Eclipse 的“包资源管理器”中,假设我有一个这样的包列表:

  • com.dog
  • com.cat
  • com.frog
  • 青蛙

If I want to rename the "com" part of the package structure to be "animal", then I could select each package (above) and perform a refactor > rename.

如果我想将包结构的“com”部分重命名为“animal”,那么我可以选择每个包(如上)并执行重构 > 重命名。

If I have many packages that start with "com", that process may take a while. Is there an easy way to rename the "com" package name without having to individually rename each package in the Package Explorer? or removing those packages from the build path before renaming?

如果我有许多以“com”开头的软件包,则该过程可能需要一段时间。是否有一种简单的方法可以重命名“com”包名称,而无需在包资源管理器中单独重命名每个包?或者在重命名之前从构建路径中删除这些包?

I tried going to the "Navigator" pane where it displays the folders in a tree structure but I am not given the rename capability.

我尝试转到“导航器”窗格,在那里它以树结构显示文件夹,但我没有重命名功能。

采纳答案by Rich Seller

By default empty parent packages are hidden in the package explorer, if you modify the Filters...in the Package Explorer to uncheck Empty Parent Packages(third from top in second screenshot) you'll be able to see the empty packages.

默认情况下,包资源管理器中隐藏了空的父包,如果您修改包资源管理中的过滤器...以取消选中Empty Parent Packages(第二个屏幕截图中倒数第三个),您将能够看到空包。

package explorer filters

包浏览器过滤器

filters view
(source: eclipse.org)

过滤器视图
(来源:eclipse.org

You can then rename the compackage and check the Rename subpackagesoption to force all child packages to be renamed.

然后,您可以重命名com包并选中重命名子包选项以强制重命名所有子包。

rename package
(source: eclipse.org)

重命名包
(来源:eclipse.org

Then when you're done reapply the filter to hide all those empty packages again.

然后,当您完成后,重新应用过滤器以再次隐藏所有这些空包。

回答by VonC

It looks like the current JDT API (Java Development Tool, the part that includes package renamming) does only rename one package at a time (and not the sub-packages)

看起来当前的 JDT API(Java 开发工具,包括包重命名的部分)一次只重命名一个包(而不是子包)

See:

看:

When refactoring a package, that has subpackages, JDT creates child packages again, instead of just renaming the parent

重构具有子包的包时,JDT 会再次创建子包,而不仅仅是重命名父包

we need an API on IPackageFragmentto rename not only the fragment but also also all subpackages.
Effectively, the implementation would rename the folder of the package fragment and then update the package declarations in all contained CUs (including those in subpackages)

我们需要一个 APIIPackageFragment来重命名片段和所有子包。
实际上,实现将重命名包片段的文件夹,然后更新所有包含的 CU(包括子包中的 CU)中的包声明

So it's "by design" at then moment (eclipse 3.5), but an enhancement is logged and will be taken into account for 3.6.

因此,当时它是“按设计”(eclipse 3.5),但会记录增强功能,并将在 3.6 中考虑在内。

Note: that "lack of feature" has been noted since 2005!

注意:自 2005 年以来已经注意到“缺乏功能”!

I was testing the new hierarchical package rename and had two source folders with same package structure. To rename the packages in both I had to do the same operation twice.
It would be nice to get a hint and being asked whether the package rename should be applied to the other source folder(s) as well.

我正在测试新的分层包重命名,并且有两个具有相同包结构的源文件夹。要重命名这两个包中的包,我必须执行两次相同的操作。
获得提示并被询问包重命名是否也应应用于其他源文件夹会很好。

回答by Christopher Klewes

Create an File in your 'com' package. Rename it and check 'Rename subpackages'. Delete the file.

在您的“com”包中创建一个文件。重命名并选中“重命名子包”。删除文件。

回答by Rich Seller

I've had a go at implementing a plugin to rename parent packages. It adds a "Rename parent package" item to the context menu of , or can be triggered by ctrl-7.

我已经尝试实现一个插件来重命名父包。它将“重命名父包”项添加到 的上下文菜单中,或者可以由 触发ctrl-7

I've not implemented the code to enable/disable the menu item based on the active selection (there's some race condition that causes the wizard to stop cancelling). If the active selection is a package with a parent package, it will select that parent and launch the rename wizard. You'll still need to select "rename subpackages" manually.

我没有实现基于活动选择启用/禁用菜单项的代码(有一些竞争条件导致向导停止取消)。如果活动选择是具有父包的包,它将选择该父包并启动重命名向导。您仍然需要手动选择“重命名子包”。

Here's the plugin code:

这是插件代码:

package name.seller.rich.packagerenamer.actions;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
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.actions.RenameAction;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;

public class RenameParentPackageHandler extends AbstractHandler {

    public RenameParentPackageHandler() {
    }

    public Object execute(ExecutionEvent event) throws ExecutionException {
        IWorkbenchPart activePart = HandlerUtil.getActivePart(event);
        try {
            IStructuredSelection selection = SelectionConverter
                    .getStructuredSelection(activePart);

            IPackageFragment parentPackage = getParentPackage(selection);

            if (parentPackage != null && parentPackage.exists()) {

                RenameAction action = new RenameAction(HandlerUtil
                        .getActiveSite(event));

                StructuredSelection parentSelection = new StructuredSelection(
                        parentPackage);
                action.run(parentSelection);
            }
        } catch (JavaModelException e) {
            logException(e);
        }
        return null;
    }

    private IPackageFragment getParentPackage(IStructuredSelection selection) {
        IJavaElement[] elements = SelectionConverter.getElements(selection);

        if (elements != null && elements.length > 0) {
            if (elements[0] != null && elements[0] instanceof IPackageFragment) {
                IPackageFragment fragment = (IPackageFragment) elements[0];

                String packageName = fragment.getElementName();
                int lastDotIndex = packageName.lastIndexOf(".");

                if (lastDotIndex != -1) {
                    String parentPackageName = packageName.substring(0,
                            lastDotIndex);

                    IJavaElement parent = fragment.getParent();
                    if (parent != null
                            && parent instanceof IPackageFragmentRoot) {

                        return ((IPackageFragmentRoot) parent)
                                .getPackageFragment(parentPackageName);

                    }
                }
            }
        }
        return null;
    }

    protected void logException(Exception e) {
        JavaPlugin.log(e);
    }
}

Here's the plugin.xml

这是 plugin.xml

<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>
<plugin>
   <extension
     point="org.eclipse.ui.commands">
      <command
        name="Rename parent package"
        categoryId="name.seller.rich.packagerenamer.category"
        id="name.seller.rich.packagerenamer.renameParentPackage">
      </command>
   </extension>
   <extension
     point="org.eclipse.ui.handlers">
      <handler
        commandId="name.seller.rich.packagerenamer.renameParentPackage"
        class="name.seller.rich.packagerenamer.actions.RenameParentPackageHandler">
      </handler>
   </extension>
   <extension
     point="org.eclipse.ui.bindings">
      <key
        commandId="name.seller.rich.packagerenamer.renameParentPackage"
        contextId="org.eclipse.ui.contexts.window"
        sequence="M1+7"
        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.packagerenamer.renameParentPackage"
           mnemonic="K">
         </command>
      </menuContribution>
   </extension>
</plugin>

And the manifest:

和清单:

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Classwizard
Bundle-SymbolicName: name.seller.rich.packagerenamer; 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 Scuba Steve

Umm, I don't know what everyone else here is doing, but in Eclipse Juno right click the packacge -> refactor -> rename

嗯,我不知道这里的其他人在做什么,但在 Eclipse Juno 中右键单击 packacge -> 重构 -> 重命名

Then just rename your packages, and check the box if you want the changes to cascade down the hierarchy.

然后只需重命名您的包,如果您希望更改在层次结构中级联,请选中该框。