Is it possible in Java to limit a generic type <T> to only some types like:
BooleanIntegerLongFloatString?
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;
}
}
Run Code Online (Sandbox Code Playgroud)
and:
Data<Integer> data = Data.newInstance(10);
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
However, you can't just restrict it to a list of arbitrary types that are inherently unrelated.
不可能使用单个声明的类型<T>,但您可以定义一个包装类,为所需类型提供工厂方法
public class Restricted<T> {
private T value;
public Restricted(T value) {
this.value = value;
}
public static Restricted<Boolean> getBoolean(Boolean value) {
return new Restricted<Boolean>(value);
}
public static Restricted<Integer> getInteger(Integer value) {
return new Restricted<Integer>(value);
}
public static Restricted<Double> getLong(Double value) {
return new Restricted<Double>(value);
}
// remaining methods omitted
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3224 次 |
| 最近记录: |