Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way with Java Generics to take Generic parameter that requires implementation of 2 interfaces?

Say I have this code -

public interface ParentInterface1 {
    public List<? extends ChildInterface1> getChildren();
    public void setChildren(List<? extends ChildInterface1> children);
}
public interface ParentInterface2 {
    public List<? extends ChildInterface2> getChildren();
    public void setChildren(List<? extends ChildInterface2> children);
}
public interface ChildInterface1 {
    public String getField();
    public void setField(String field);
}
public interface ChildInterface2 {
    public String getField();
    public void setField(String field);
}
public class LParentImpl implements ParentInterface1, ParentInterface2 {
    private List<ChildImpl> list;
    public List<ChildImpl> getChildren() {
        return list;
    }
    public void setChildren(List<... wants to accept ChildImpl, which 
                                   implements ChildInterface1 & ChildInterface2> children) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
public class ChildImpl implements ChildInterface1, ChildInterface2 {
    private String field;
    public String getField() {
        return field;
    }
    public void setField(String field) {
        this.field = field;
    }
}

Is there a way to make the setChildren() in the ParentImpl class work, without removing the Generic typing completely from the interfaces and implementation?

I'd like to do something like -

public void setChildren(List<? extends ChildInterface1 & ChildInterface2> children) 

This sort of interface/implementation structure is valid for non Generic types, but it seems some aspect of the run-time erasure of Generics might make this impossible? Or am I missing some magic syntax?

Edit: Using the List<? extends ChildInterface1 & ChildInterface2> yields this compile error -

...\ParentImpl.java:20: > expected
    public void setChildren(List<? extends ChildInterface1 & ChildInterface2> children) {
like image 478
Richard Nichols Avatar asked Dec 01 '22 07:12

Richard Nichols


1 Answers

You can specify a method that takes an object that implements those two interfaces like this:

public <T extends IFirst & ISecond> void doSomething(T obj) {}

However, it won't matter much in your example, since both your child interfaces specify the same methods.

like image 178
Jorn Avatar answered Dec 03 '22 21:12

Jorn