Here is what I'm trying to do:
I have this piece of code:
Object selectedCreditId = null;
int i = 0;
String selectedCreditName = leasing.getCredit().getDisplayName();
Collection<DCredRating> selectCreditIds = creditData.getItemIds();
for (DCredRating id: selectCreditIds) {
String creditItem = id.getDisplayName();
if (selectedCreditName.equals(creditItem)) {
selectedCreditId = creditData.getIdByIndex(i);
}
i++;
}
I want to create function using this code. The function will take leasing
class and creditData
BeanItemContainer as parameters and return selectedCreditId
object.
In other words something like this:
private Object getSelectedCreditId(LeasingResP param, BeanItemContainer<...> param2) {
Object selectedCreditId = null;
int i = 0;
LeasingResP leasing = param;
BeanItemContainer<...> creditData = param2;
String selectedCreditName = leasing.getCredit().getDisplayName();
Collection<...> selectCreditIds = creditData.getItemIds();
for (... id: selectCreditIds) {
String creditItem = id.getDisplayName();
if (selectedCreditName.equals(creditItem)) {
selectedCreditId = creditData.getIdByIndex(i);
}
i++;
}
}
The problem here is that creditData
container can be of different class.
Is there any "pretty" way of doing this, or I'll have to write an if block(s) for different classes?
If you are really not interested on the type of beans that are collected in the container you could declare the method as following:
private Object getSelectedCreditId(LeasingResP param, BeanItemContainer<?> param2) {
...
}
The "?" means container of unknown type, so you only know about your beans that they are of type Object
.
You could also make the method generic, so that it returns the correct type:
private <T extends DCredRating> T getSelectedCreditId(LeasingResP param, BeanItemContainer<? extends T> param2) {
...
}
A usage for that second variant would be (an example):
LeasingResP param = ...
BeanItemContainer<DCredRating> container = ...
DCredRating dcr = getSelectedCreditId(param, container);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句