1700448471
1700448472
public static<T>Class<T>getGenricClassType(Class clz){
1700448473
1700448474
Type type=clz.getGenericSuperclass();
1700448475
1700448476
if(type instanceof ParameterizedType){
1700448477
1700448478
ParameterizedType pt=(ParameterizedType)type;
1700448479
1700448480
Type[]types=pt.getActualTypeArguments();
1700448481
1700448482
if(types.length>0&&types[0]instanceof Class){
1700448483
1700448484
//若有多个泛型参数,依据位置索引返回
1700448485
1700448486
return(Class)types[0];
1700448487
1700448488
}
1700448489
1700448490
}
1700448491
1700448492
return(Class)Object.class;
1700448493
1700448494
}
1700448495
1700448496
}
1700448497
1700448498
前面我们讲过,Java的泛型类型只存在于编译期,那为什么这个工具类可以取得运行期的泛型类型呢?那是因为该工具只支持继承的泛型类,如果是在Java编译时已经确定了泛型类的类型参数,那当然可以通过泛型获得了。例如有这样一个泛型类:
1700448499
1700448500
abstract class BaseDao<T>{
1700448501
1700448502
//获得T的运行期类型
1700448503
1700448504
private Class<T>clz=Utils.getGenricClassType(getClass());
1700448505
1700448506
//根据主键获得一条记录
1700448507
1700448508
public void get(long id){
1700448509
1700448510
session.get(clz, id);
1700448511
1700448512
}
1700448513
1700448514
}
1700448515
1700448516
//操作user表
1700448517
1700448518
class UserDao extends BaseDao<String>{
1700448519
1700448520
}
[
上一页 ]
[ :1.700448471e+09 ]
[
下一页 ]