简体   繁体   中英

Java Generic Type non-static method return Object instead of generic type T

public class Module<T> {

    @SuppressWarnings("unchecked")
    public <T> T module(Class<T> clazz) {
        return clazz.cast(this);
    }
        
}

This is the base class of my module and I want to initialize it to TestModule by calling the module method above.

TestingModule testingModule = new Module().module(TestingModule.class);

However, the return type of

new Module().module(TestingModule.class)

is Object instead of TestingModule. Is there any idea that I can directly initialize it without using any casting or changing the method to static ?

There are a few problems. The one most directly linked to the type mismatch error is here:

TestingModule testingModule = new Module().module(TestingModule.class);

new Module() is using Module without any type argument. When you use a raw type like this, you lose all generic information in the expression. You can fix it simply by adding a type argument:

TestingModule testingModule = new Module<String>().module(TestingModule.class);

In the above code, I've added <String> to the constructor call, which resolves the problem. But String is as strange a type argument as it can get in this case, which leads to the following side note.

The declaration public <T> T module(Class<T> clazz) adds a type variable T that hides the class-level type variable of the same name. If this method is not made generic by accident, please use a different name for this variable, and use it . Otherwise, this method doesn't need to be generic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM