Generic class that accepts either of two types

后端 未结 3 1120
猫巷女王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: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 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");
      }
      

提交回复
热议问题