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

时间:2012-02-04 15:30:38

标签: java generics

我想制作这种形式的通用类:

class MyGenericClass<T extends Number> {}

问题是,我想接受T为Integer或Long,但不是Double。所以只有两个可接受的声明是:

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

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:30)

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

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>类型的变量,但它必须为空。

答案 1 :(得分:2)

不,Java泛型中没有任何内容允许这样做。您可能需要考虑使用由FooIntegerImplFooLongImpl实现的非通用接口。如果不了解更多关于你想要实现的目标,很难说。

答案 2 :(得分:0)

您要求的类可以接受两种类型之一。上面已经回答了。但是,我还将回答如何将这个想法扩展到您正在使用的类中的方法,而无需为此创建另一个类。您只想使用:-

  • 整数
  • 不是Double

    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");
    }
    
相关问题