How to create instance of the unkown type?

后端 未结 2 1315
慢半拍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:45

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


    However, the generics are unnecessary:

    private  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 _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 doWork1(T _obj) { ... }
      

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

提交回复
热议问题