Generic class that accepts either of two types

后端 未结 3 1112
猫巷女王i
猫巷女王i 2020-12-03 06:24

I want to make a generic class of this form:

class MyGenericClass {}

Problem is, I want to be acceptable for T to b

相关标签:
3条回答
  • 2020-12-03 07:16

    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.

    0 讨论(0)
  • 2020-12-03 07:18

    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.

    0 讨论(0)
  • 2020-12-03 07:25

    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 : -

    • Integer
    • Long
    • 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");
      }
      
    0 讨论(0)
提交回复
热议问题