Generic method to print map of different object types with same name belongs to different classes

Viewed 152

I am trying to write a generic method to print map of different object types with same name belongs to different classes :

private<T> void print(T obj) {
    //Some proecssing on obj.keySet()
    obj.getMapOfObjects().values().stream().forEach(System.out::println);
}

for 2 classes B and C, as follows.

 public class B implements A {
    private Map<Object, List<String>> mapOfObjects = new HashMap<>();
    
    public void setMapOfObjects(Map<Object, List<String>> mapOfObjects) {
        this.mapOfObjects = mapOfObjects;
    }
    
    public Map<Object, List<String>> getMapOfObjects() {
        return mapOfObjects;
    }
}

and

public class C implements A {

    private Map<Integer, List<String>> mapOfObjects = new HashMap<>();

    public void setMapOfObjects(Map<Integer, List<String>> mapOfObjects) {
        this.mapOfObjects = mapOfObjects;
    }
    
    public Map<Integer, List<String>> getMapOfObjects() {
        return mapOfObjects;
    }
}

A does not have getMapOfObjects() method as return types are different.

I am getting exception on line obj.getMapOfObjects().values() as "method getMapOfObjects() undefined on type T". I want to understand whether I can write above method by the use of generics or functions in java 8 and if yes then how to write?

1 Answers

The compiler does not know what <T> is in that first method. What if it is an instance of String, which does not have a getMapOfObjects method? You have to specify a type for <T>.

You know that <T> should be an instance of A (am I correct in this?), so you can fix the compiler error by specifying this like so:

private <T extends A> void print(T obj) {
    // Some proecssing on obj.keySet()
    obj.getMapOfObjects().values().stream().forEach(System.out::println);
  }
Related