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(“我不会处理你们很多”);
    }
    

我考虑过这一点,它会解决我的问题。我只是想知道java泛型是否允许我在不必声明此类的情况下完成这项工作。但我不会使用接口,因为这两个类的实现是相同的。我将创建一个抽象包保护类,并创建两个扩展它的公共类。至于我要实现的,我想创建一个对Integer、Long或任何其他类似int的类型有意义的类,但对浮点类型使用它没有意义。那么使用泛型的好处在哪里呢?由于生成一个具有类型为T的参数的方法将接受代码中的任何数字,因此它肯定不是。因为无法编写接受T类型参数的方法。您必须为每个此类方法编写两个单独的定义,一个用于Integer,另一个用于Long。@djaqeel这不是真的。如果您尝试将frob方法与长或整数以外的其他对象一起使用,您将得到一个编译器异常。