
本文档旨在指导开发者如何从一个包含不同类型对象的 List<CommonDTO> 中安全有效地获取 CustId。文章将介绍几种常见的设计模式和代码实现,包括类型判断、接口定义、继承以及Stream API的使用,并提供相应的代码示例,帮助读者选择最适合自己场景的方案,保证代码的健壮性和可维护性。
最直接的方法是使用 instanceof 关键字判断 CommonDTO 对象的实际类型,然后将其强制转换为对应的类型,并调用相应的 getCustId() 方法。
public String getCustId(CommonDTO dto) {
if (dto instanceof Emp) {
return ((Emp)dto).getCustId();
}
if (dto instanceof Student) {
return ((Student)dto).getCustId();
}
return null;
}优点: 简单易懂,适用于类型数量较少的情况。
缺点: 代码可扩展性差,如果新增类型,需要修改 getCustId() 方法,违反了开闭原则。此外,如果对象没有 CustId 属性,可能导致 ClassCastException。
定义一个包含 getCustId() 方法的通用接口 Customer,让 Emp 和 Student 类都实现该接口。
public interface Customer {
String getCustId();
}
public class Emp implements CommonDto, Customer {
private String custId;
public String getCustId() { return custId; }
// 其他属性和方法
}
public class Student implements CommonDto, Customer {
private String custId;
public String getCustId() { return custId; }
// 其他属性和方法
}然后,可以通过以下方式获取 CustId:
public String getCustId(CommonDTO dto) {
if (dto instanceof Customer) {
return ((Customer)dto).getCustId();
}
return null;
}优点: 提高了代码的可扩展性,新增类型只需要实现 Customer 接口即可。
缺点: 需要修改现有的类结构,引入新的接口。
创建一个 Customer 类,继承 CommonDTO,并在 Customer 类中定义 custId 属性和 getCustId() 方法。然后,让 Emp 和 Student 类继承 Customer 类。
public class Customer extends CommonDTO {
private String custId;
public String getCustId() { return custId; }
// 其他属性和方法
}
public class Emp extends Customer {
// 其他属性和方法
}
public class Student extends Customer {
// 其他属性和方法
}获取 CustId 的方式与方法二类似:
public String getCustId(CommonDTO dto) {
if (dto instanceof Customer) {
return ((Customer)dto).getCustId();
}
return null;
}优点: 与方法二类似,提高了代码的可扩展性。
缺点: 引入了继承关系,可能增加代码的复杂性。
可以使用 Java 8 的 Stream API 来简化从 List<CommonDTO> 中获取 CustId 的过程。
List<String> customerIds = commonList.stream()
.filter(c -> c instanceof Customer) // 过滤出 Customer 类型的元素
.map(c -> (Customer)c) // 将 CommonDTO 转换为 Customer
.map(Customer::getCustId) // 获取 CustId
.collect(Collectors.toList()); // 将 CustId 收集到 List 中优点: 代码简洁,易于阅读。
缺点: 需要 Java 8 或更高版本。
选择哪种方法取决于具体的应用场景和需求。
无论选择哪种方法,都应该注意以下几点:
希望本文档能够帮助你更好地从 List<CommonDTO> 中获取 CustId。
以上就是从包含不同对象的 List 中安全获取 CustId 的最佳实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号