当我反映genericType时,我有一些问题。首先,我有一个像这样的类声明:
System.out.print("Enter name:");
name=sc.nextLine();
System.out.print("Enter nric: ");
nric=sc.nextLine();
System.out.print("Enter age: ");
age=sc.nextInt();
sc.nextLine();// for consuming the nextLine
System.out.print("Enter gender(male/female): ");
gender=sc.nextLine();
System.out.print("Enter weight:");
weight=sc.nextInt();
System.out.print("Enter height: ");
height=sc.nextDouble();
T是:
public class JoyPageWebDTO<T> {
private int recordCount;
private int pageSize;
private int pageIndex;
private List<T> records;
}
请求后的JoyPageWebDTO结果如下: [http://i.stack.imgur.com/zeK1O.jpg][1]
问题是如何从public class AuditSpuWebDTO implements Serializable {
private String indications;
private String forbidden;
private int shopID;
private String shopName;
private String city;
private Date updateTime;
private int auditStatus;
private String auditContent;
}
获取T(AuditSpuWebDTO
)?我希望得到JoyPageWebDTO
的值。我写了一些代码来处理这个问题,然而,失败了!
AuditSpuWebDTO
当我反映泛型类型:来自List的T时,结果的类型为public static void reflect(Class<?> clazz) {
for (Field field : clazz.getDeclaredFields()) {
//get the static type of the field
Class<?> fieldType = field.getType();
//if it's String,
if (fieldType == String.class) {
// save/use field
}
//if it's String[],
else if (fieldType == String[].class) {
// save/use field
}
//if it's List or a subtype of List,
else if (List.class.isAssignableFrom(fieldType)) {
//get the type as generic
ParameterizedType fieldGenericType = (ParameterizedType) field.getGenericType();
//get it's first type parameter
Type type = fieldGenericType.getActualTypeArguments()[0];
Class<?> fieldTypeParameterClazz;
if (type instanceof ParameterizedType) {
fieldTypeParameterClazz = (Class<?>) ((ParameterizedType) type).getRawType();
} else if(type instanceof TypeVariable){
//todo how to get the class????
}else{
fieldTypeParameterClazz = (Class<?>) type;
}
//if the type parameter is String,
if (fieldTypeParameterClazz == String.class) {
// save/use field
}
}
}
}
,如何从TypeVariable
获取Class<?>
?我标记的TypeVariable
是我的关键问题。
答案 0 :(得分:0)
List
唯一了解它的通用类型是它的名称为T
由于Java使用类型擦除,因此无法在运行时获取此信息。可以获得的是当您将特定类型编译到类中时,例如
// create a subclass of ArrayList with a specific type.
List<String> list = new ArrayList<String>() { };
但是,普通List
或ArrayList
没有编译到该类中的类型,因此无法从中检索更多信息。