Generic class that accepts either of two types

后端 未结 3 1130
猫巷女王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: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 {
      public static MyGenericClass newInstance(Long value) {
        return new MyGenericClass(value);
      }
    
      public static MyGenericClass newInstance(Integer value) {
        return new MyGenericClass(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 and MyGenericClass instances can be created. Though you can still declare an variable of type MyGenericClass it will just have to be null.

提交回复
热议问题