Java: how do I get a class literal from a generic type?

后端 未结 8 1310
北荒
北荒 2020-11-22 07:18

Typically, I\'ve seen people use the class literal like this:

Class cls = Foo.class;

But what if the type is generic, e.g. List?

8条回答
  •  清酒与你
    2020-11-22 08:15

    To expound on cletus' answer, at runtime all record of the generic types is removed. Generics are processed only in the compiler and are used to provide additional type safety. They are really just shorthand that allows the compiler to insert typecasts at the appropriate places. For example, previously you'd have to do the following:

    List x = new ArrayList();
    x.add(new SomeClass());
    Iterator i = x.iterator();
    SomeClass z = (SomeClass) i.next();
    

    becomes

    List x = new ArrayList();
    x.add(new SomeClass());
    Iterator i = x.iterator();
    SomeClass z = i.next();
    

    This allows the compiler to check your code at compile-time, but at runtime it still looks like the first example.

提交回复
热议问题