本文介绍了Java反射:Method.getGenericXXXXX方法如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚注意到有一个以及和类似的异常对类型和参数类型。
I just noticed there's a Method.getGenericReturnType()
as well as Method.getReturnType()
and similar pairs for exception types and parameter types.
我认为Java中的泛型通过类型擦除工作。那么这些方法在运行时如何工作? (以及我将在运行时使用它们)
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?)
推荐答案
具有具体类型声明部分的泛型(方法,类,参数)被保留下来。
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
}
这篇关于Java反射:Method.getGenericXXXXX方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!