Are generics removed by the compiler at compile time

后端 未结 4 741
陌清茗
陌清茗 2020-12-17 21:19

In this tutorial on reflection it states:

[...] because generics are implemented via type erasure which removes all information regarding generic typ

4条回答
  •  情书的邮戳
    2020-12-17 21:47

    Some generics stay in the compiled class -- specifically including method signatures and class definitions, for example. At runtime, no objects keep their full generic type, but even at runtime you can look up the generic definition of a class or a method.

    For example, if you have

    class Foo {
      List getList() { ... }
    
      public static void main(String[] args) {
        System.out.println(Foo.class.getMethod("getList").getGenericReturnType());
        // prints "List"
        List list = new Foo().getList();
        // there is no way to get the "String" parameter on list
    }
    

提交回复
热议问题