Automatic convert inheritance to delegation

时间:2016-04-04 17:04:22

标签: java intellij-idea

Automated delegation in Java

In the link above, the user asks a similar question but the answer given required using reflection.

My question is whether is a refactoring tool that will automatically generate all the one-liner method for each of the delegating class automatically.

Intellij offers a "Replace inheritance with delegation" tool, but it doesn't do the job properly - when I use it creates a big mess of duplicate methods and other weird behavior that makes it worse than actually doing it manually (I think it's because multiple interfaces it tries to delegate that are clashing with each other and causing a whole mess.

Am I doing it wrong or perhaps it's a bug or limitation in IntelliJ?

Any workaround that I can use instead of spending my time copy-pasting code?

EDIT:

I've isolated the problem as follow (each class is in a separate file of course):

class TestClass extends MyClass {
    void function() {}
}
class MyClass extends MyAbstractClass implements MyInterface {
    @Override
    void function() {}
}
abstract class MyAbstractClass {
    abstract void function();
}
interface MyInterface {
    void function();
}

Now, if I use "Replace Inheritance With Delegation" on TestClass I get the following result:

class TestClass implements MyInterface {
    private final MyMyClass myClass = new MyMyClass();

    void function() {
        myClass.function();
    }

    void function() {
        myClass.function();
    }

    private class MyMyClass extends MyClass {
        void function() {}
    }
}

So function() appears twice, which I believe should not since naturally the code can't compile with two function with identical signature, forcing me to manually remove one of them which is tedious with actual classes with many functions with the same signature

Try it for example with MyClass<E> extends HashSet<E> and see what a mess it becomes. I could select the specific functions to delegate and make sure I don't select only 1 method with identical signatures, but this makes this whole refactoring pointless - it would be faster for me to just write the forwarding functions myself...

1 个答案:

答案 0 :(得分:1)

生成覆盖所有方法的子类,然后将super.替换为delegate.。有些IDE甚至有这个选项。