Get type of generic type inside a List in Java

前端 未结 7 2306
天命终不由人
天命终不由人 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:35

    It is not possible to determine this due to erasure, which means that the parameter is not stored in the code. However you can either pass an extra parameter specifying what type the list is:

    public <T> void putList(String key, List<T> lst, Class<T> listElementType) {
    

    }

    or you can determine the type of each element at runtime:

    public <T> void putList(String key, List<T> lst){
      for (Object elem:lst) {
          if (elem instanceof String) {
          // Do something       
          }
          if (elem instanceof Integer) {
          // Do something   
          }
      }
    }
    
    0 讨论(0)
  • 2021-02-15 23:37

    Use the instanceof operator.

    That said, generic operations should be, well, generic, so be wary of changing behaviour based on type.

    0 讨论(0)
  • 2021-02-15 23:37
    Type genericType = lst.getType();
    
    if(genericType instanceof ParameterizedType){
        ParameterizedType aType = (ParameterizedType) genericType;
        Type[] fieldArgTypes = aType.getActualTypeArguments();
        for(Type fieldArgType : fieldArgTypes){
            Class fieldArgClass = (Class) fieldArgType;
            System.out.println("fieldArgClass = " + fieldArgClass);
        }
    }
    
    0 讨论(0)
  • 2021-02-15 23:45

    You can not find the type of T as the type information is erased. Check this for more details. But if the list is not empty, you can get an element from the list and can find out using instanceof and if else

    0 讨论(0)
  • 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 <T> void putList(String key, List<T> list, Class<T> 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<String> {
        private List<String> 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.

    0 讨论(0)
  • 2021-02-15 23:56

    If you want to run function of the object, you can do:

    public <T> void putList(String key, List<T> lst){
        for(T object : lst){
             if(object instanceof String) {
                 doSomething(((String)object).doForString())
             }
             if(object instanceof Integer) {
                 doSomething(((Integer)object).doForInteger())
             }
        }
    }
    
    0 讨论(0)
提交回复
热议问题