I didn’t manage to compile a set of classes with nested interfaces.
Let’s assume there are two interfaces:
public interface IntA
{
public Map<String, ? extends IntB> getName();
public void setName(Map<String, ? extends IntB> name);
}
public interface IntB
{
long getId();
void setId(long id);
}
and two corresponding implementation classes
public class ImplA implements IntA,Serializable
{
private Map<String, ImplB> name;
public Map<String, ? extends IntB> getName(){return name;}
public void setName(Map<String, ? extends IntB> name)
{this.name = (Map<String, ImplB>)name;}
}
public class ImplB implements IntB,Serializable
{
private long id;
public long getId() {return id;}
public void setId(long id) {this.id = id;}
}
How can i use the setter of ImplA?
public static void create(Random rnd, String code)
{
ImplB b = new ImplB();
b.setId(1);
ImplA a = new ImplA();
a.getName().put("key", b);
a.getName().put("key", (IntB)b);
}
results in:
put(java.lang.String,capture#50 of ? extends IntB) in
java.util.Map<java.lang.String,capture#50 of ? extends .IntB>
cannot be applied to (java.lang.String,ImplB)
put(java.lang.String,capture#845 of ? extends IntB) in
java.util.Map<java.lang.String,capture#845 of ? extends IntB>
cannot be applied to (java.lang.String,IntB)
Thank you
Thor
Your getter is returning a more general type. Imagine if it the actual return value was a reference to a
Map<String, SomeOtherImplB>– you wouldn’t want to be able to put anImplBthere.If you want to be able to put a value into a
Map, you either need the value type to be specified exactly, or specified with a “super” constraint rather than an “extends” constraint. For example:So that’s why it’s not working at the moment. As for the right way to work around that… it’s hard to know exactly what you’re trying to do. Maybe you want to change it to:
… or the alternative is to make
IntAgeneric:So in this case, your
ImplAclass would implementIntA<ImplB>.