gpt4 book ai didi

java - 接受两种类型之一的泛型类

转载 作者:IT老高 更新时间:2023-10-28 21:06:28 25 4
gpt4 key购买 nike

我想做一个这种形式的泛型类:

class MyGenericClass<T extends Number> {}

问题是,我希望 T 可以是整数或长整数,但不是 double 。所以仅有的两个可接受的声明是:

MyGenericClass<Integer> instance;
MyGenericClass<Long> instance;

有什么办法吗?

最佳答案

答案是否定的。至少没有办法使用泛型类型来做到这一点。我建议结合泛型和工厂方法来做你想做的事。

class MyGenericClass<T extends Number> {
public static MyGenericClass<Long> newInstance(Long value) {
return new MyGenericClass<Long>(value);
}

public static MyGenericClass<Integer> newInstance(Integer value) {
return new MyGenericClass<Integer>(value);
}

// hide constructor so you have to use factory methods
private MyGenericClass(T value) {
// implement the constructor
}
// ... implement the class
public void frob(T number) {
// do something with T
}
}

这确保只有 MyGenericClass<Integer>MyGenericClass<Long>可以创建实例。尽管您仍然可以声明 MyGenericClass<Double> 类型的变量它必须为空。

关于java - 接受两种类型之一的泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9141960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com