I want to make a generic class of this form:
class MyGenericClass {}
Problem is, I want to be acceptable for T to b
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.
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.
You asked for a class that accepts either of two types. That has already been answered above. However I will also answer how you can extend that idea to a method within the class you are using without need for creating another class for this. You want to use just : -
Not 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");
}