Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a method which accepts any collection of classes which extend Throwable?

Tags:

java

generics

I want to pass a collection of classes which extend Throwable to a method. However, my attempt fails to compile 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 make it compile by changing the calling code to:

foo(Collections.<Class<? extends Throwable>>singleton(RuntimeException.class));

but I'd rather not force clients to write this obtuse generic type. Is it possible to write a method which will take any collection of classes which subtype Throwable?

EDIT:

Someone fixed the above example with the method signature:

public <T extends Throwable> void foo(Collection<Class<T>> c) {}

But I'm now having problems using the parameter. Specifically, I want to assign it to a field, like this:

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>>
like image 937
MikeFHay Avatar asked Dec 26 '22 14:12

MikeFHay


1 Answers

Use

public <T extends Throwable> void foo(Collection<Class<T>> c) {}
like image 62
Someone Avatar answered Apr 05 '23 23:04

Someone