泛型编程记录

public interface A{
}
一,通过Class类获取泛型

1 public class B implements interface A
当需要获取到泛型参数的类型时可以采用以下几种
1)Class<?> class = B.getGenericInterfaces()[0].getActualTypeArguments;
但是无法采用下列一种
A b = new B(){};
Class<?> class = b.getClass().getGenericInterfaces()[0].getActualTypeArguments;
采用这种方式返回的不是ParameterrizedTypeImpl类型,无法获取到泛型参数

2 public class B implements interface A
当B为带泛型的类时,实例化B的时候需要传入具体的类,泛型的类型就确定了,可以采用
A b = new B(){};// Timpl为具体的类,不是泛型
Class<?> class = b.getClass().getGenericInterfaces()[0].getActualTypeArguments;

3 public interface B extends interface A {

}
若想获取B的泛型参数,可以采用下列方式:
Class<?> ob = Class.forName(“com.opsoft.infrastructure.mapper.TestMapper”);

    Type[] types = ob.getGenericInterfaces();
	Class<?> type = types[0].getActualTypeArguments;

二,通过spring bean获取泛型
public class B implements interface A{
}
A b = new B();
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(b.getClass());

defaultListableBeanFactory.registerBeanDefinition(“b”, beanDefinitionBuilder.getBeanDefinition());

A b1 = (A) ctx.getBean(“b”);
Class<?> class = b1.getClass().getGenericInterfaces()[0].getActualTypeArguments()
这样也可以获取泛型参数

进一步,当服务接口中传入泛型mapper和entity时,根据bean获取到service的mapper和entity,
再进行接口的查询,结果转化封装。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值