I have a method that takes a generic parameter type. The scenario I have is this method will be called with different parameter types.
class something{
public void someMethod(){
List<A> listA = ....; //Class A have a field String Id;
List<B> listB = ....; //Class B haave a field String Id;
testMethod(listA);
testMethod(listB);
}
private <T> void testMethod( List<T> list ){
for( T event : list ){
//TODO (something like): event.getId();
}
}
}
In the above code all the parameters will be be a List<someObjectType>
. All the object types have a common field and need to use the getter to fetch its value. Now since the method definition is generic, how do I achieve this?
Generics Work Only with Reference Types: When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);
You have to add the numbers as the same type, so you could do x. intValue() + y. intValue(); .
Have A
and B
implement a common interface that has a method getID
:
interface SomeInterface {
String getID();
}
then you could have:
private <T extends SomeInterface> void testMethod(List<T> list) {
for (T event : list) {
// now you can use `event.getID()` here
}
}
There is no point in creating such a generic method without bounded type. Since T isn't bounded to any type, you can't use specific interface on the objects inside the list. So if you want testMethod to get list of objects of any type, you should use List<?>
instead.
This cannot be done. You can't handle two different lists with incompatible interfaces the same way in your method, unless you do something with instanceof
, i.e.
public void testMethod(List<? extends Object> list) {
if(list.get(0) == null) return;
if(list.get(0) instanceof A) {
// Do the A stuff
} else {
// Do the B stuff
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With