Class object of generic class (java)

前端 未结 7 915
时光说笑
时光说笑 2020-11-27 03:17

is there a way in java to get an instance of something like Class> ?

相关标签:
7条回答
  • 2020-11-27 03:17

    You could use Jackson's ObjectMapper

    ObjectMapper objectMapper = new ObjectMapper();
    CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(List.class, ElementClass.class)
    

    No unchecked warnings, no empty List instances floating around.

    0 讨论(0)
  • 2020-11-27 03:21

    how about

    (Class<List<Object>>)(Class<?>)List.class
    
    0 讨论(0)
  • 2020-11-27 03:29
    List.class
    

    the specific type of generics is "erased" at compile time.

    0 讨论(0)
  • 2020-11-27 03:32
    public final class ClassUtil {
        @SuppressWarnings("unchecked")
        public static <T> Class<T> castClass(Class<?> aClass) {
            return (Class<T>)aClass;
        }
    }
    

    Now you call:

    Class<List<Object>> clazz = ClassUtil.<List<Object>>castClass(List.class);
    
    0 讨论(0)
  • 2020-11-27 03:37

    As mentioned in other answers, Class represents an erased type. To represent something like ArrayList<Object>, you want a Type. An easy way of getting that is:

    new ArrayList<Object>() {}.getClass().getGenericSuperclass()
    

    The generic type APIs introduced in 1.5 are relatively easy to find your way around.

    0 讨论(0)
  • 2020-11-27 03:42

    You can get a class object for the List type using:

    Class.forName("java.util.List")
    

    or

    List.class
    

    But because java generics are implemented using erasures you cannot get a specialised object for each specific class.

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