附录一有某种方法接受<代码>List<?>。
public void method(List<?> list) {
// some logic
}
我怎样才能在运行时间获得这一要素类型? 是否可能?
I found these suggestions (here on SO):
((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]
(doesn t work,List
is an interface and doesn t have a superclass)
// ChatGPT s work
public class App {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
List<Integer> integerList = new ArrayList<>();
Type stringType = getListElementType(stringList);
Type integerType = getListElementType(integerList);
System.out.println("String List Element Type: " + stringType.getTypeName());
System.out.println("Integer List Element Type: " + integerType.getTypeName());
}
private static Type getListElementType(List<?> list) {
Type genericType = list.getClass().getGenericSuperclass();
if (genericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericType;
return parameterizedType.getActualTypeArguments()[0];
}
throw new IllegalArgumentException("Unable to determine list element type.");
}
}
青春期产出:
String List Element Type: E
Integer List Element Type: E
- Storing a corresponding class as a field during creation of a generic class instance (doesn t work,
List
is read-only, and it can t have any instance fields anyway since it s an interface)
/*
from jqno s answer to "How can I learn actual type argument of an generic class?"
Henning in his answer to "Get generic type of class at runtime" suggested a similar trick
*/
class ParameterizedClass<T> {
private Class<T> type;
/** Factory method */
public static <T> ParameterizedClass<T> of(Class<T> type) {
return new ParameterizedClass<T>(type);
}
/** Private constructor; use the factory method instead */
private ParameterizedClass(Class<T> type) {
this.type = type;
}
// Do something useful with type
}
- The TypeTools library. I still need some supertype
类型Resolver类别提供了以下几种方法:
Type reify(Type type, Class<S> context)
采用从具体情况中可变信息的类型,回归类型完全重新调整。
<编码> 类型重新编号(Type generalType)
Returns a fully reified genericType using information from the generic declaration.
Class<?>>。
解决使用亚甲苯类变异信息的类型方面的原始论点。
Class<?>solRawArgument (Class<T>打字、分类和提字;S> subType)
解决使用亚甲苯的类型变异信息的类型方面的原始论点。
<编码> 类型决定
采用亚类变异信息的类型确定通用类型。
Class<?>solRawClass (Type general) 类型、类别和类别; 和; 次级类型:
普通类原产阶级 使用亚丁那类变量信息的类型。