Java reflection: how do the Method.getGenericXXXXX

2019-05-08 16:48发布

问题:

I just noticed there's a Method.getGenericReturnType() as well as Method.getReturnType() and similar pairs for exception types and parameter types.

I thought generics in Java worked via type erasure. So how would these methods work at runtime? (and what would I use them for at runtime?)

回答1:

Generics that have concrete types part of declarations (methods, fields, classes, arguments) are retained.

So you can obtain the types from this declaration

 public List<String> toString(List<Foo> foos) { .. }

But you can't from this code:

public List<E> transform(List<E> list) {
  // E is not accessible at runtime
}


回答2:

Generics may work by erasure, but code which uses your compiled classes still need to use generics correctly. There is additional information there for the compiler, which you can get, but this doesn't change its runtime behaviour.