Reputation: 643
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
Reputation: 18834
This can be done using the "Generate delegated method" feature:
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;
}
Right click after the local s
variable and press "generate"
Select "Delegate Methods" in the popup, followed by the local s
variable
Select everything you want to override
(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