简体   繁体   English

在 Eclipse 中,如何将匿名接口实现重构为 Enum Singleton

[英]In Eclipse, how to refactor anonymous interface implementation to Enum Singleton

Let's say I have an interface:假设我有一个界面:

public interface Foo{
    String bar(int baz);
}

Now in some Java code I have an anonymous implementation of that interface:现在在一些 Java 代码中,我有该接口的匿名实现:

Foo foo = new Foo(){
    public String bar(int baz){
        return String.valueOf(baz);
    }
};

Is there a way (in Eclipse) to refactor this to the enum singleton pattern (Effective Java, Item 3), like this:有没有办法(在 Eclipse 中)将其重构为枚举 singleton 模式(有效的 Java,第 3 项),如下所示:

// further up in the same Compilation Unit:
enum StandardFoo implements Foo{
    INSTANCE{
        public String bar(int baz){
            return String.valueOf(baz);
        }
    }
}

// ...
Foo foo = StandardFoo.INSTANCE;

This refactoring is tedious to do by hand and I do it all the time.手动进行这种重构很乏味,我一直都在这样做。 Is there any plugin that does that?有没有可以做到这一点的插件? Or a secret JDT trick I don't know about (I'm using Indigo)?还是我不知道的秘密 JDT 技巧(我正在使用 Indigo)?

BTW: do Idea or NetBeans support this refactoring?顺便说一句:Idea 或 NetBeans 是否支持这种重构?

There is no way.不可能。

btw, it would be more usual to do something like this:顺便说一句,做这样的事情会更常见:

enum StandardFoo implements Foo {
    INSTANCE1(0),
    INSTANCE2(5);

    private final int delta;

    private StandardFoo(int delta) {
        this.delta = delta;
    }

    public String bar(int baz) {
        // Simple example to demonstrate using fields in enum methods
        return String.valueOf(baz + delta); 
    }
}

FYI even though they are defined as "INSTANCE1(0)", you still refer to them as just "INSTANCE1" in code;仅供参考,即使它们被定义为“INSTANCE1(0)”,您仍然在代码中将它们称为“INSTANCE1”; ie StandardFoo.INSTANCE1.bar(123) etcStandardFoo.INSTANCE1.bar(123)

Perhaps adding a private field to the enum to assist with the implementation of the method, set via a (private) constructor.也许向枚举添加一个私有字段以帮助实现该方法,通过(私有)构造函数设置。

The refactoring "Convert anonymous class to nested" does a part of the trick.重构“将匿名 class 转换为嵌套”起到了部分作用。 You have to change the class into an enum and replace the ctor call by the enum singleton.您必须将 class 更改为枚举并将 ctor 调用替换为枚举 singleton。

IDEA supports Structural Search and Replace (Tutorial), which I believe could speed this up for you. IDEA 支持结构搜索和替换(教程),我相信这可以为您加快速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM