开发者

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:

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:

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

// ...
开发者_JS百科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)?

BTW: do Idea or NetBeans support this refactoring?


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; ie StandardFoo.INSTANCE1.bar(123) etc

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. You have to change the class into an enum and replace the ctor call by the enum singleton.


IDEA supports Structural Search and Replace (Tutorial), which I believe could speed this up for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜