Imagine to have a java class
public class FixedClassOfStrings {
List<String> myMember=new ArrayList<String>();
// omissed all non relevant code...
public Class getMyType() {
return String.class;
}
}
How can I make it paramteric, by using java generics?
My attempts fail:
public class GenericClass<T> {
List<T> myMember=new ArrayList<T>();
public Class getMyType() {
return T.class; // this gives "Illegal class literal for the type parameter T"
}
}
Also, how can I avoid warning: "Class is a raw type. References to generic type Class should be parameterized" in the FixedClassOsStrings? is it ok to declare:
public Class<String> getMyType() {
return String.class;
}
...
And if it is ok, what shall I return using generics?
public Class<T> getMyType() {
return T.class; // this gives "Illegal class literal for the type parameter T"
}
...
All hints will be appreciated!!!
I would try something like this:
public Class<T> getMyType() {
return /* some instance of T */.getClass();
}
Alternatively, an easy solution is passing the instance upon construction:
public class YourClass<T> {
private final Class<T> type;
public YourClass (/* arguments */, Class<T> type) {
this.type = type;
}
public Class<T> getType() {
return this.type;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With