我有一個對象,它有幾個數組作爲字段。這是類大致是這樣的:獲得類似對象屬性的通用方法
public class Helper {
InsuranceInvoices[] insuranceInvoices;
InsuranceCollectiveInvoices[] insuranceCollectiveInvoices
BankInvoices[] bankInvoices;
BankCollectiveInvoices[] bankCollectiveInvoices;
}
所有發票類型都有一個共同的標記接口發票。
我需要獲得所有的發票來調用其他方法。
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-loops不必要地膨脹了代碼。
有沒有一種方法可以編寫一般(私有)方法?一個想法是:
private void generalMethod(Invoice[] invoiceArray){
// ...
}
但是這將需要四個instanceof檢查,因爲該類發票不知道方法getCusomterId()。所以我什麼也得不到。該方法仍然包含重複。
我很感謝所有可能的解決方案來推廣這個問題!
這樣,所有類實現'Invoice',並都實現'getCustomerId',但' getCustomerId'不在'Invoice'界面中?您必須使用反射才能按名稱訪問方法並調用它。此時,「發票」界面是無用的。 – njzk2
是否getInsuranceInvoices','getBankInvoices' ...所有四個返回相同數量的發票? – Rajesh
我有一個建議...將一個線索應用到使'發票'接口成爲標記接口的人而不是一個指定發票具有共同點的方法的人。 – Powerlord