Can capture in Java generics be unified in type declarations?

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 = ...;

, , : - , - ?

+5
6

Generics of Higher Kind. Java , , . , Java, , Scala . , ​​ , .

+3

.

, Map "special" - Function, ? , " ", - , Agda , Agda .

, , API, . Guava ClassToInstanceMap. ​​ .

+2

public static <T extends Exception> void foo(Class<T> cl, List<? super T> ls) throws Exception {
    ls.add(cl.newInstance());
}

? " Java" ( )

+1

, "" - , , . , , Map.Entry.

.

, Map, put get, scoped . addAll(), Java.

0

, , - Map :

public class ClassMap<T extends Foo> extends HashMap<Class<T>, T>

, - .

0

, .

, .

public void foo(Class<? extends Exception> cl, List<? extends Exception> ls) throws Exception;

public void foo(Class<Integer> c1, List<String> ls) throws Exception

, , .

, , .

public <T extends Exception> void foo(Class<T> cl, List<T> ls) throws Exception

, , , Exception class

, , ? super T, T .

public <T extends Exception> void foo(Class<T> cl, List<? super T> ls) throws Exception

" - , - ?"

, .

public class Foo<T extends Exception> { 

   private Map<Class<T>,T> map;

   public void T getFoo(Class<T> clazz) {
     return map.get(clazz);
   }

}

, , .

So, the final solution for you is that if you create an encapsulated map and use the correct method for installing and retrieving objects, then an invalid warning is not true. Because you provided type safety in another way.

0
source

All Articles