Reputation: 41117
I'm having this problem. Shouldn't the constructor have the same type parameters as the class?
public class MyBuilder<T> {
private final Class<T> clss;
/**
*
* @param clss
*/
public <T> MyBuilder(final Class<T> clss) {
this.clss = (Class<T>) clss; // compiler error here
}
Type mismatch: cannot convert from java.lang.Class<T> to java.lang.Class<T>
If I remove the <T>
for the ctor it compiles, but I cannot do :
MyBuilder<Foo> myBuilder = new MyBuilder<Foo>(); // compiler error here
The error is The constructor MyBuilder<Foo>()
is undefined.
Upvotes: 1
Views: 3503
Reputation: 55233
Remove the type parameter from the constructor, as well as the cast:
public MyBuilder(final Class<T> clss) {
this.clss = clss;
}
The type parameters of a class, T
in this case, are implicitly declared for any instance members, including constructors. By explicitly declaring T
for the constructor you were actually masking the T
declared by the class, causing that confusing error.
Upvotes: 8
Reputation: 9330
Because this "T" is not that "T". T is just a "place holder" for some type. The T in
private final Class<T> clss;
is unrelated to the T in the constructor parameter.
Upvotes: 5