Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this generic method accept any type?

Tags:

java

generics

In the code below, when I call getList() I am not able to specify <T>. getList<T>() does not compile.

Instead, I may only call getList() - but then <T> is always simply <Event> .

Why is this?

class Foo
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // For the sake of a complete example - the next method has
        // my question.
        Foo f = new Foo();
        f.register(new Subscriber<MyEvent>() {
            public void handle(MyEvent event){};
        });
    }

    public <T extends Event> void register(Subscriber<T> subscriber) {

        // Below won't work. I can't specify <T>, so getList()
        // will return a HashSet<Subscriber<Event>>, to which I cannot
        // add the Subscriber<T>!

        getList().add(subscriber);

        // Why can't I call getList<T>().add(subscriber) ?

    }

    private <T extends Event> HashSet<Subscriber<T>> getList() {
        // For the sake of example, simply return a new HashSet.
        return new HashSet<Subscriber<T>>();
    }
}

interface Subscriber<T extends Event> {
    public void handle(T event);
}

interface Event { }
class MyEvent implements Event { }
like image 749
ledneb Avatar asked Dec 20 '25 16:12

ledneb


1 Answers

It appears that Java won't accept a <T> as the type argument to a simple name such as getList(). But it will accept it if you explicitly state this. when calling the method:

this.<T>getList().add(subscriber);
like image 66
rgettman Avatar answered Dec 22 '25 06:12

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!