Is it possible in Java to limit a generic type <T>
to only some types like:
Boolean
Integer
Long
Float
String
?
Edit: My problem is to limit a generic type <T>
to different class types which have not common direct superclass.
Edit: I finally use the scheme proposed by Reimeus:
public class Data<T> {
private T value;
private Data(T value) {
this.set(value);
}
public static Data<Integer> newInstance(Integer value) {
return new Data<Integer>(value);
}
public static Data<Float> newInstance(Float value) {
return new Data<Float>(value);
}
public static Data<String> newInstance(String value) {
return new Data<String>(value);
}
public T get() {
return this.value;
}
public void set(T value) {
this.value = value;
}
}
and:
Data<Integer> data = Data.newInstance(10);
Edit: Another approach:
public class Data<T> {
private T value;
private Data(T value) {
this.set(value);
}
@SuppressWarnings("unchecked")
public Data(Integer value) {
this((T) value);
}
@SuppressWarnings("unchecked")
public Data(Float value) {
this((T) value);
}
@SuppressWarnings("unchecked")
public Data(String value) {
this((T) value);
}
public T get() {
return this.value;
}
public void set(T value) {
this.value = value;
}
}
But I have a problem with it:
If by mistake the data
instance is declared with:
Data<Integer> data = new Data<Integer>(3.6f); // Float instead of Integer
There is no class cast exception and data.get()
returns 3.6
I don't understand why...
So, the first solution seems better.
You can restrict it by polymorphism, eg:
<T super X> //Matches X and all superclasses of X
<T extends X> //Matches X and all subclasses of X
However, you can't just restrict it to a list of arbitrary types that are inherently unrelated.
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