How to create instance of the unkown type?

后端 未结 2 1298
慢半拍i
慢半拍i 2021-01-25 08:18

I have a couple of functions which requires exact argument type (aka T):

private  void doWork1(T _obj) {...}
private  void doWork2         


        
相关标签:
2条回答
  • 2021-01-25 08:28

    User the type Number for your obj. Integer and Double both extend this type.

    The abstract class {@code Number} is the superclass of platform classes representing numeric values that are convertible to the primitive types {@code byte}, {@code double}, {@code float}, {@code int}, {@code long}, and {@code short}.

    public void parse(int id)
    {
        Number obj = null;
        switch (id)
        {
            case 1:
            {
                obj = new Integer(1);
                break;
            }
            case 2:
            {
                obj = new Double(2);
                break;
            }
        }
        doWork1(obj);
        doWork2(obj);
        doWork3(obj);
    }
    

    If you do not want to be this concrete, you can always use Object.

    0 讨论(0)
  • 2021-01-25 08:45

    You can use Number or Object, which are both common supertypes of Integer and Double.


    However, the generics are unnecessary:

    private <T> void doWork1(T _obj) {...}
    

    is identical to

    private void doWork1(Object _obj) {...}
    

    after erasure.

    The only point of having a type variable for an input parameter is if:

    • You need to indicate that the generics of another input parameter need to be related, e.g. you are passing T _obj and List<T> _list.

      Note that you don't need a generic type for T _obj1 and T _obj2, though - that degenerates to the upper bound of T (e.g. Object);

    • If you need it to be related to the return type:

      <T> T doWork1(T _obj) { ... }
      

    You don't need either case here, so just remove the unnecessary complication.

    0 讨论(0)
提交回复
热议问题