我有一个对象,它有几个数组作为字段。它的类大致是这样的:
public class Helper {
InsuranceInvoices[] insuranceInvoices;
InsuranceCollectiveInvoices[] insuranceCollectiveInvoices
BankInvoices[] bankInvoices;
BankCollectiveInvoices[] bankCollectiveInvoices;
}
所有发票类型都有一个相互标记接口Invoices。
我需要获取所有发票才能对其调用另一种方法。
Helper helperObject = new Helper();
// ...
for (InsuranceInvoices invoice : helperObject.getInsuranceInvoices()) {
Integer customerId = invoice.getCustomerId();
// ...
}
for (BankInvoices invoice : helperObject.getBankInvoices()) {
Integer customerId = invoice.getCustomerId();
// ...
}
// repeat with all array fields
问题是所有发票只有共同的标记界面。getCustomerID()方法不是由相互接口或类定义的。由于给定的规范,这是我无法改变的行为。
for-each-loop 中的代码重复让我很头疼。我必须对四个不同数组中的所有发票对象执行完全相同的操作。因此,有四个 for-each-loop 不必要地使代码膨胀。
有没有办法可以编写通用(私有)方法?一个想法是:
private void generalMethod(Invoice[] invoiceArray){
// ...
}
但这需要四次 instanceof 检查,因为Invoice类不知道getCusomterId()方法。因此,我将一无所获;该方法仍将包含重复。
我感谢所有可能的解决方案来概括这个问题!