Consider the following Java function:
public void foo(Class<? extends Exception> cl, List<? extends Exception> ls) throws Exception {
ls.add(cl.newInstance());
}
It does not work, because the anchor types cland lsare not united and can actually refer to different types. If this function were compiled, I could name it foo(NullPointerException.class, new List<SecurityException>()), which would be illegal.
We can fix this, obviously, by combining captures like, for example:
public <T extends Exception> void foo(Class<T> cl, List<T> ls) throws Exception {
ls.add(cl.newInstance());
}
Now this function works as expected. So, to my question: is there a way to unify type capture in a single type declaration?
For example, I often find a map that maps classes to instances of themselves. The only way I can do this now is to have a companion function that does unchecked casts:
private Map<Class<? extends Foo>, ? extends Foo> map = ...;
@SuppressWarnings("unchecked")
private <T extends Foo> T getFoo(Class<T> cl) {
return((T)map.get(cl));
}
, , , . , , :
<T extends Foo> Map<Class<T>, T> map = ...;
, , : - , - ?