Possible solutions to summarize the problem (ordered from best to worst):
Using a wrapper class
public class InvoiceWrapper { private String customerID; public String getCustomerID() { return customerID; } public InvoiceWrapper(BankInvoices invoice) { this.customerID = invoice.getCustomerID(); } public InvoiceWrapper(InsuranceInvoices invoice) { this.customerID = invoice.getCustomerID(); }
Update . If I understand correctly, you need to do something with identifiers in all arrays. To use InvoiceWrapper, you also need to implement an iterator in the Helper class, which will go through arrays and return a wrapper for each record. Thus, in any case, you will have code that works with 4 arrays.
Using cast instance
public class CustomerIdHelper { public static String getID(Invoice invoice) { if (invoice instanceof InsuranceInvoices) { return ((InsuranceInvoices) invoices).getCustomerID(); } else if ... } }
Calling methods by name via Reflection
public class CustomerIdHelper { public static String getID(Invoice invoice) { Method method = invoice.getClass().getDeclaredMethod("getCustomerId"); return (String) method.invoke(invoice); } }
AdamSkywalker
source share