Generic class that accepts either of two types

The answer is no. At least there is no way to do it using generic types. I would recommend a combination of generics and factory methods to do what you want.

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
  }
}

This ensures that only MyGenericClass<Integer> and MyGenericClass<Long> instances can be created. Though you can still declare an variable of type MyGenericClass<Double> it will just have to be null.


No, there's nothing in Java generics to allow this. You might want to consider having a non-generic interface, implemented by FooIntegerImpl and FooLongImpl. It's hard to say without knowing more about what you're trying to achieve.

Tags:

Java

Generics