Reputation: 21
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?
Upvotes: 0
Views: 674
Reputation: 45319
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.
Upvotes: 1