TypeVariable 检测与转换 type instanceof TypeVariable (TypeVariable<?>) type

TypeVariable 检测与转换

type instanceof TypeVariable

检查 type 是不是泛型参数(如 T、E)

class Box<T> { }  // T 是 TypeVariable

Type type = Box.class.getTypeParameters()[0];
boolean isTypeVar = type instanceof TypeVariable; // true

(TypeVariable<?>) type

把 type 转成 TypeVariable 类型来使用

TypeVariable<?> typeVar = (TypeVariable<?>) type;
String name = typeVar.getName(); // 得到 "T"

完整流程

if (type instanceof TypeVariable) {
    // 确定是泛型参数后,强制转换
    TypeVariable<?> typeVar = (TypeVariable<?>) type;
    // 现在可以调用 TypeVariable 的方法
    return resolveTypeVar(typeVar, srcType, declaringClass);
}

一句话理解

先检查是不是泛型参数,如果是就转成对应类型来使用

// 如果字段值不同,则记录该字段的更新 if (!Objects.equals(oldValue, newValue)) { String fieldName = field.getAnnotation(ApiModelProperty.class).value(); // 处理嵌套对象 // 使用注解判断字段类型 EntityField entityField = field.getAnnotation(EntityField.class); if (entityField != null) { if (oldValue instanceof Serializable && newValue instanceof Serializable) { Class<?> fieldType = field.getType(); String nestedLog = compareEntity((Serializable) oldValue, (Serializable) newValue, fieldType, null, null, null, false); if (!nestedLog.isEmpty()) { fieldChanges.add("【" + fieldName + "】中的子对象更新如下:\n" + nestedLog); } } else if (oldValue instanceof Collection && newValue instanceof Collection) { // 处理嵌套对象列表 Class<?> fieldType = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0].getClass(); String nestedLog = compareList((List<?>) oldValue, (List<?>) newValue, fieldType, null, null, null, false); if (!nestedLog.isEmpty()) { fieldChanges.add("【" + fieldName + "】中的子对象列表更新如下:\n" + nestedLog); } //处理列表存在旧数据为null的情况 }else if ( oldValue == null && newValue instanceof Collection) { Class<?> fieldType = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0].getClass(); fieldChanges.add("【" + fieldName + "】中的子对象列表更新如下:\n" + nestedLog); } } else { fieldChanges.add("【" + fieldName + "】由【" + oldValue + "】更新为【" + newValue + "】\n"); // 添加换行符 } }如果列表中旧列表是null如何
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值