Java reflection: how do the Method.getGenericXXXXX

2019-05-08 16:15发布

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?)

2条回答
爷、活的狠高调
2楼-- · 2019-05-08 16:44

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
}
查看更多
The star\"
3楼-- · 2019-05-08 17:05

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.

查看更多
登录 后发表回答