Java 接受两种类型之一的泛型类
我想创建此表单的泛型类:Java 接受两种类型之一的泛型类,java,generics,Java,Generics,我想创建此表单的泛型类: class MyGenericClass<T extends Number> {} class MyGenericClass{} 问题是,我希望T可以是整数或长的,但不能是双精度的。因此,只有两种可接受的声明: MyGenericClass<Integer> instance; MyGenericClass<Long> instance; MyGenericClass实例; MyGenericClass实例; 有什么方法可以做
class MyGenericClass<T extends Number> {}
class MyGenericClass{}
问题是,我希望T可以是整数或长的,但不能是双精度的。因此,只有两种可接受的声明:
MyGenericClass<Integer> instance;
MyGenericClass<Long> instance;
MyGenericClass实例;
MyGenericClass实例;
有什么方法可以做到这一点吗?没有,Java泛型中没有允许这样做的东西。您可能想考虑拥有一个非通用接口,它由代码> FooPixErgIMPL/<代码>和
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
}
}
class MyGenericClass{
公共静态MyGenericClass newInstance(长值){
返回新的MyGenericClass(值);
}
公共静态MyGenericClass newInstance(整数值){
返回新的MyGenericClass(值);
}
//隐藏构造函数,因此必须使用工厂方法
私有MyGenericClass(T值){
//实现构造函数
}
//…实现类
公共无效frob(T编号){
//用T做点什么
}
}
这确保只能创建
MyGenericClass
和MyGenericClass
实例。尽管您仍然可以声明类型为MyGenericClass
的变量,但它必须为null。您要求的类接受两种类型中的任何一种。以上已经回答了这个问题。然而,我还将回答您如何将这个想法扩展到您正在使用的类中的方法,而无需为此创建另一个类。您只想使用:-
- 整数
- 长的
- 不加倍
private <T extends Number> T doSomething(T value) throws IllegalArgumentException{ if(value instanceof Integer){ return (Integer)value; } else if(value instanceof Long){ return new value.longValue(); } else throw new IllegalArgumentException("I will not handle you lot"); }
private T doSomething(T值)抛出IllegalArgumentException{ if(值instanceof Integer){ 返回(整数)值; } else if(值instanceof Long){ 返回新值。longValue(); } 其他的 抛出新的IllegalArgumentException(“我不会处理你们很多”); }