关键词搜索

源码搜索 ×
×

Java ?不定类型与泛型的使用解决List继承参数

发布2022-05-25浏览936次

详情内容

?表示不确定的数据类型。下面我们来看看怎么使用。

定义模型和子模型

  1. @Data
  2. public class Model {
  3. String id;
  4. String name;
  5. String desc;
  6. }
  7. @Data
  8. public class SubModel extends Model{
  9. String subName;
  10. }

定义List泛型接口和实现

  1. public interface MultiModelService {
  2. /**
  3. * 多模型List
  4. * @param list
  5. */
  6. void batchSave(List<? extends Model> list);
  7. }
  8. @Slf4j
  9. @Service
  10. public class MultiModelServiceImpl implements MultiModelService {
  11. @Override
  12. public void batchSave(List<? extends Model> list) {
  13. log.info("--MultiModelService batchSave--");
  14. }
  15. }

编写测试用例

  1. @ComponentScan(basePackages = "com.boonya.code.list.service.impl")
  2. @SpringBootTest
  3. @SpringBootConfiguration
  4. public class TestMultiModelService {
  5. @Autowired
  6. MultiModelService multiModelService;
  7. @Test
  8. public void test(){
  9. List<Model> models = new ArrayList<>();
  10. List<SubModel> subModels = new ArrayList<>();
  11. multiModelService.batchSave(models);
  12. multiModelService.batchSave(subModels);
  13. }
  14. }

输出效果: 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载