Issue with Generic interface

I am facing one issue with generic implementation. Below is the code:

public interface Response<S, T> {

 public void response(S data, T... arg);
}

public class CustomerDetail<XYZ, PQR> implements Response<XYZ, PQR> {
  @Override
  public void response(XYZ data, PQR... args) {
    PQR request = args[0];
    Map reportMap = data.any();
    //do something
  }
}


public class EmployeeDetail<ABC, DEF> implements Response<ABC, DEF> {
  @Override
  public void response(ABC data, DEF... args) {
     List reportList = data.getDetails();
    //do something
  }
}

Also , class XYZ, ABC looks like below:

public class XYZ {
   public Map any() {
     //do something
     return mapObject;
  }
}

public class ABC {
   public List getDetails() {
     //do something
     return listObject;
  }
}

During compilation , i am getting the compilation error:

cannot find method any();
cannot find the method getDetails();

Earlier i tried with this code, and it was working fine:

public class CustomerDetail<S, T> implements Response<S, T> {
  @Override
  public void response(S data, T... args) {
    PQR request = (PQR)args[0];
    Map reportMap = ((XYZ)data).any();
    //do something
  }
}


public class EmployeeDetail<S, T> implements Response<S, T> {
  @Override
  public void response(S data, T... args) {
     List reportList = ((ABC)data).getDetails();
    //do something
  }
}

But i dont want the typecasting of generic variables. So i followed the above approach. I tried to follow the link Any idea, where i am making mistake. Thanks

Answer

You are close, but you are shadowing classes with generic types.

This declaration (with superfluous public removed):

public interface Response<S, T> {
    void response(S data, T... arg);
}

Takes any types S and T, so this class:

public class CustomerDetail<XYZ, PQR> implements Response<XYZ, PQR> {
  @Override
  public void response(XYZ data, PQR... args) {
    PQR request = args[0];
    Map reportMap = data.any();
    //do something
  }
}

Merely redefines the generic type variables S -> XYZ and T -> ABC. You haven’t specified concrete types here, you have merely defined generic type variables that happen to have the same name as your classes.

If you want a class to extend a specific generic type, it should not have type definitions:

public class CustomerDetail implements Response<XYZ, PQR> {
  @Override
  public void response(XYZ data, PQR... args) {
    PQR request = args[0];
    Map reportMap = data.any();
    //do something
  }
}

As a side note, as you are playing with generics, you should know that the definition of List is List<E> and the definition of Map is Map<K, V> – they’re also generic. Don’t use rawtypes.

Leave a Reply

Your email address will not be published. Required fields are marked *