Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java method returning an instance of Class<T extends Somethng>

i've got this code:

public <T extends Scrapper> Class<T> getScrapper() {
    return MyScrapper.class;
}

MyScrapper is a class implementing Scrapper interface. Why is this not working? U'm getting the following error in JDK7:

error: incompatible types
required: Class<T>
found:    Class<MyScrapper>
where T is a type-variable:
T extends Scrapper declared in method <T>getScrapper()

P.S. I've honestly tried searching for whole 30-40 minutes.

Update: if i declare the method as public Class<? extends Scrapper> getScrapper() { it works. but I still don't understand why the original declaration was not compiling. what's wrong with it?

like image 672
Yervand Aghababyan Avatar asked Apr 24 '12 22:04

Yervand Aghababyan


1 Answers

With a generic method like getScrapper(), the caller of the method determines what the actual type argument to the method is (T in this case). The caller could pick any subtype of Scrapper as T, and your method (which always returns MyScrapper.class) would not be returning the correct class.

Given the signature of the method, the caller of this method would expect to be able to do this:

Class<MyOtherScrapper> c = foo.<MyOtherScrapper>getScrapper();

Changing the method to return Class<? extends Scrapper> makes it no longer a generic method... there are no type parameters for the caller to set. Instead, the signature says that the method returns the class object for some unknown subtype of Scrapper, and MyScrapper.class does fit the bill for that.

like image 96
ColinD Avatar answered Oct 19 '22 20:10

ColinD