3

For example, I want to extend HashSet class, but instead of extending the class, I give my new class a private field that references an instance of the existing class. Each instance method in the new class invokes the corresponding method on the contained instance of the existing class and returns the result. This is a composition and forwarding approach.

I.e. for instance, I want IDE to generate the ForwardingSet class based on Set:

public class ForwardingSet<E> implements Set<E> {
     private final Set<E> s;

     public ForwardingSet(Set<E> s){ 
            this.s = s; 
     }

     public boolean contains(Object o){ 
            return s.contains(o); 
     }

     public boolean isEmpty(){
            return s.isEmpty();
     }


... and etc.

}

So, how I can generate it in the Idea?

P.S: a similar question is here, but without answers.

Aleksei Sotnikov
  • 633
  • 4
  • 15
  • [Creating and Editing file templates](https://www.jetbrains.com/help/idea/creating-and-editing-file-templates.html) – gkhaos Mar 26 '18 at 07:45
  • I think templates are not intended for this because of a lot of questions still open: How to generate forwarding method? How to generate constructor? – Aleksei Sotnikov Mar 26 '18 at 08:23

1 Answers1

7

This can be done using the "Generate delegated method" feature:

  1. Create a basic class containing only the field you want to delegate to:

    public class ForwardingSet<E> implements Set<E> {
         private final Set<E> s;
    }
    
  2. Right click after the local s variable and press "generate"

  3. Select "Delegate Methods" in the popup, followed by the local s variable

  4. Select everything you want to override

  5. (Optional) Use copy and replace to replace public by @Override public and then manually remove it for the first public in the file, to get rid of all override warnings

Ferrybig
  • 18,194
  • 6
  • 57
  • 79
  • It is almost what I currently do. And it is tedious. I am looking for "one-step" solution. – Aleksei Sotnikov Mar 26 '18 at 08:19
  • Furthermore, this approach leads to human errors. Just let's imagine a forwarding class with 100+ methods. – Aleksei Sotnikov Mar 26 '18 at 08:29
  • If you forgot to select 1 method, you hopefully get an error because the fact you don't implement a method from the interface. If I need to do this, this is usually the way I also do it myself (but inside a different editor since Intellij is not my primary editor) – Ferrybig Mar 26 '18 at 08:30
  • Tested in IDEA 2018.3, the @Override annotations don't need to be manually added any more. – a.l. Jan 04 '19 at 01:49