I want to make a generic class of this form:
class MyGenericClass<T extends Number> {}
Problem is, I want to be acceptable for T to be either Integer or Long, but not Double. So the only two acceptable declarations will be:
MyGenericClass<Integer> instance;
MyGenericClass<Long> instance;
Is there any way to do that?
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.