Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using getter with java generic method argument

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?

like image 451
broun Avatar asked Dec 04 '12 20:12

broun


People also ask

How do you pass a generic argument in Java?

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);

How do you add two generic values in Java?

You have to add the numbers as the same type, so you could do x. intValue() + y. intValue(); .


3 Answers

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
    }
}
like image 85
arshajii Avatar answered Sep 25 '22 18:09

arshajii


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.

like image 21
axelrod Avatar answered Sep 21 '22 18:09

axelrod


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
  }
}
like image 42
durron597 Avatar answered Sep 25 '22 18:09

durron597