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