Ответ - нет. По крайней мере, нет способа сделать это с использованием универсальных типов. Я бы порекомендовал сочетание обобщенных и заводских методов, чтобы делать то, что вы хотите.
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>
, она просто должна быть нулевой.