Can I call .class on a generic type in Java?

前端 未结 3 1100
[愿得一人]
[愿得一人] 2021-01-02 00:40

I was wondering if there is a way in Java to do something like

Class c = List.class;
Class c2 = List.class;

I nee

相关标签:
3条回答
  • 2021-01-02 00:52

    No, it is not possible. You can't even refer to List<String>.class in your code - it results in a compilation error. There is only one single class object for List, and it is called List.class.

    Is this not possible because of type erasure during runtime ?

    Correct.

    Btw this is a generic type, not an annotated type.

    Update

    On second thought, you can have something fairly close to your Map above, by tweaking Josh Bloch's typesafe heterogenous container (published in Effective Java 2nd Ed., Item 29) a bit:

    public class Lists {
        private Map<Class<?>, List<?>> lists =
                new HashMap<Class<?>, List<?>>();
    
        public <T> void putList(Class<T> type, List<T> list) {
            if (type == null)
                throw new NullPointerException("Type is null");
            lists.put(type, list);
        }
    
        public <T> List<T> getList(Class<T> type) {
            return (List<T>)lists.get(type);
        }
    }
    

    The cast in getList is unchecked, giving a warning, but I am afraid we can't avoid that. However, we know that the value stored for class X must be a List<X>, as this is guaranteed by the compiler. So I think the cast is safe (if you play by the rules, that is - i.e. never call putList with a plain nongeneric Class parameter), thus it can be suppressed using @SuppressWarnings("unchecked").

    And you can use it like this:

    Lists lists = new Lists();
    List<Integer> integerList = new ArrayList<Integer>();
    List<String> stringList = new ArrayList<String>();
    ...
    
    lists.putList(Integer.class, integerList);
    lists.putList(String.class, stringList);
    List<Integer> storedList = lists.getList(Integer.class);
    
    assertTrue(storedList == integerList);
    
    0 讨论(0)
  • 2021-01-02 01:05

    It is not possible as you are trying.
    But you could decorate these lists and create a MyListDates and MyListString instead and store them in the hashmap

    0 讨论(0)
  • 2021-01-02 01:13

    You can't to it quite like this, but you can achieve your overall aim using the same approach as Guice does with TypeLiteral. If you're using Guice already, I suggest you use that directly - otherwise, you might want to create your own similar class.

    Essentially the idea is that subclasses of a generic type which specify type arguments directly retain that information. So you write something like:

    TypeLiteral literal = new TypeLiteral<List<String>>() {};
    

    Then you can use literal.getClass().getGenericSuperclass() and get the type arguments from that. TypeLiteral itself doesn't need to have any interesting code (I don't know whether it does have anything in Guice, for other reasons).

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