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,
再进行接口的查询,结果转化封装。