I want to pass a set of classes that extend a method Throwableto a method. However, my attempt was not compiled in Netbeans with jdk1.6.0_39:
package com.memex.sessionmanager;
import java.util.Collection;
import java.util.Collections;
public class GenericsDemo
{
public void foo(Collection<Class<? extends Throwable>> c)
{
}
public void bar()
{
foo(Collections.singleton(RuntimeException.class));
}
}
The compiler says foo(java.util.Collection<java.lang.Class<? extends java.lang.Throwable>>) in com.memex.sessionmanager.GenericsDemo cannot be applied to (java.util.Set<java.lang.Class<java.lang.RuntimeException>>).
I can compile it by changing the call code to:
foo(Collections.<Class<? extends Throwable>>singleton(RuntimeException.class));
but I would rather not force clients to write this dumb generic type. Is it possible to write a method that takes any set of classes, a subtype Throwable?
EDIT:
Someone fixed the above example using the method signature:
public <T extends Throwable> void foo(Collection<Class<T>> c) {}
But now I have problems with the parameter. In particular, I want to assign it to a field, for example:
package com.memex.sessionmanager;
import java.util.Collection;
import java.util.Collections;
public class GenericsDemo
{
private Collection<Class<? extends Throwable>> throwables;
public <T extends Throwable> void foo(Collection<Class<T>> c)
{
throwables = c;
}
public void bar()
{
foo(Collections.singleton(RuntimeException.class));
}
}
But the compiler says:
incompatible types
found : java.util.Collection<java.lang.Class<T>>
required: java.util.Set<java.lang.Class<? extends java.lang.Throwable>>