Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic class that accepts either of two types

Tags:

java

generics

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?

like image 285
Rafael Avatar asked Feb 04 '12 15:02

Rafael


2 Answers

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.

like image 161
luke Avatar answered Oct 02 '22 16:10

luke


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.

like image 39
Jon Skeet Avatar answered Oct 02 '22 16:10

Jon Skeet