Java - Generics with lists

后端 未结 5 989
悲&欢浪女
悲&欢浪女 2020-12-21 13:52

I wrote a function for my cache to retrieve a specific object. This way I don\'t need to cast it .

@SuppressWarnings(\"unchecked\")
    public static 

        
相关标签:
5条回答
  • 2020-12-21 14:16

    Just to clarify Joe's answer ( I don't have enough reputation to comment), at runtime there is no difference between a List <String> and List<Integer> or any other type of List, generics aren't kept at runtime.

    Meaning, List<String>.class is completely identical to List<Integer>.class and is actually List.class. This is a weakness of the Java type system. I'm not familiar with a simple way to implement what you wish for.

    A code proof for the heck of it :

    // It is true that      
        List<String> stringList = new ArrayList<String>(); 
        List<Integer> integerList = new ArrayList<Integer>();                                               
        System.out.println( stringList.getClass() == integerList.getClass()  );
    
        // And that ... 
        List objectList = new ArrayList();
        System.out.println( stringList.getClass() == objectList.getClass()  );
    
        //However, the following is false because a different implementation is used ( I wanted a false case)
        List objectLinkedList = new LinkedList();
        System.out.println(  objectLinkedList.getClass() == objectList.getClass() );
    
    0 讨论(0)
  • 2020-12-21 14:17

    You can't get class of List<String>, in your case the only way is:

    List<String> ipList = (List<String>)Util.inCache(List.class, title);
    
    0 讨论(0)
  • 2020-12-21 14:27

    There is a concept in java called type erasure. Due to legacy reasons, something like List is just a list. It doesn't remember that it is a list of string at run time. You should just write List.class.

    You can then specify the type of object in the List when iterating through it.

    0 讨论(0)
  • 2020-12-21 14:30

    You can try :

    List<String> ipList = Util.inCache(List.class, title);
    
    0 讨论(0)
  • 2020-12-21 14:35

    Try this-

    List<String> inList = (List<String>)Test.inCache(List.class, title);
    

    And you can do also -

    List<String> inList = Test.inCache((Class<? extends List<String>>)List.class, token);
    
    0 讨论(0)
提交回复
热议问题