Aleksei Sotnikov
Aleksei Sotnikov

Reputation: 643

Does Intellij Idea IDE has a feature to composite Java classes (forwarding class generation)

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.

Upvotes: 3

Views: 400

Answers (1)

Ferrybig
Ferrybig

Reputation: 18834

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

Upvotes: 7

Related Questions