gpt4 book ai didi

来自规范名称的 java.lang.reflect.Type

转载 作者:行者123 更新时间:2023-12-01 09:27:10 25 4
gpt4 key购买 nike

是否可以从 java.lang.reflect.Type 的规范名称实例化它?

例如,从“java.util.List”创建一个类型。

谢谢

最佳答案

一种类型,java.lang.Class也实现java.lang.reflect.Type

换句话说,你可以简单地写

java.lang.reflect.Type listType=java.util.List.class;

java.lang.reflect.Type listType=Class.forName("java.util.List");

如果类型是泛型,则 Class 实例可以代表其原始类型或泛型(可参数化)类型,具体取决于上下文,例如

static void checkType(Class<?> type, Class<?> implemented) {
if(!implemented.isAssignableFrom(type)) {
System.out.println(type+" is not a subtype of "+implemented);
}
else if(implemented.isInterface()) {
for(Type t: type.getGenericInterfaces()) {
if(t==implemented) {
System.out.println(type+" implements raw "+implemented);
}
else if(t instanceof ParameterizedType) {
ParameterizedType pt=(ParameterizedType)t;
if(pt.getRawType()==implemented) {
System.out.println(type+" implements "+implemented+" with");
TypeVariable<?>[] p = implemented.getTypeParameters();
Type[] actual = pt.getActualTypeArguments();
assert p.length==actual.length;
for(int i=0; i<actual.length; i++)
System.out.println("\t"+p[i]+" := "+actual[i]);
}
}
}
}
}

 

abstract class RawList implements List {}
checkType(RawList.class, List.class);
abstract class StringToIntMap implements Map<String,Integer> {}
checkType(StringToIntMap.class, Map.class);

打印

class Test$1RawList implements raw interface java.util.List
class Test$1StringToIntMap implements interface java.util.Map with
K := class java.lang.String
V := class java.lang.Integer

关于来自规范名称的 java.lang.reflect.Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39745100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com