Get type of generic type inside a List in Java

前端 未结 7 2303
天命终不由人
天命终不由人 2021-02-15 23:01

I have the below function:


    public  void putList(String key, List lst){
          if (T instanceof String) {
          // Do something              


        
7条回答
  •  旧巷少年郎
    2021-02-15 23:52

    It's not possible in Java due to erasure. What most people do instead is add a type token. Example:

    public  void putList(String key, List list, Class listElementType) {
    }
    

    There are certain situations where reflection can get at the type parameter, but it's for cases where you've pre-set the type parameter. For example:

    public class MyList extends List {
        private List myField;
    }
    

    In both of those cases reflection can determine the List is of type String, but reflection can't determine it for your case. You'd have to use a different approach like a type token.

提交回复
热议问题