Reputation: 3183
I have a list of beans (List<AClass>
), from which I am creating two sub list based some logic which involves checking a field from the bean class, say action. if
bean.getAction.equals("true") - add to new sublist - List<AClass> listA
else - add to new sublist - List<AClass> listB
I have created a method for it and it works fine.
Now I have similar task for other Bean class as well where i have List<BClass>
which also has action field and getAction method. I want to create a generic method which would cater to both these beans (and other similar beans as well).
How can I create such method?
Upvotes: 3
Views: 94
Reputation: 65811
Something like this should work:
interface HasAction {
public String getAction();
}
public class AClass implements HasAction {
private final String action;
public AClass (String action) {
this.action = action;
}
@Override
public String getAction() {
return action;
}
}
public class BClass implements HasAction {
private final String action;
public BClass (String action) {
this.action = action;
}
@Override
public String getAction() {
return action;
}
}
public <T extends HasAction> List<T> subList(List<T> list) {
List<T> subList = new ArrayList<T> ();
for ( T source : list ) {
if ( source.getAction().equals("true")) {
subList.add(source);
}
}
return subList;
}
Upvotes: 1
Reputation: 159754
If AClass
and BClass
share a common base then a wilcard type can be used - List<? extends CommonBase>
Upvotes: 3
Reputation: 24561
Use List<? extends ParentClass>
where ParentClass
is parent of AClass
and BClass
Upvotes: 3