Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics interface implementation

Tags:

java

generics

I have an interface as follows,

public interface MethodExecutor {
    <T> List<T> execute(List<?> facts, Class<T> type) throws Exception;
}

Also, I have a generic implementation like below,

public class DefaultMetodExecutor implements MethodExecutor {

   public <T> List<T> execute(List<?> facts, Class<T> type) throws Exception
   {
     List<T> result = null;

      //some implementation

      return result;
  }
}

Upto this there is no compilation issues,

But a specific implementation of this interface fails to compile, The one which shown below.

public class SpecificMetodExecutor implements MethodExecutor {

   public <Model1> List<Model1> execute(List<Model2> facts, Class<Model1> type) throws Exception
   {
     List<Model1> result = null;

     //some implementation specific to Model1 and Model2

      return result;
  } 
}

How can I implement this interface for some of the defined objects? Do I need to go for class level generics?

like image 459
Nandan Avatar asked Dec 11 '22 15:12

Nandan


2 Answers

You need to make T a class type parameter, not a method type parameter. You can't override a generic method with a non-generic method.

public interface MethodExecutor<T> {
    List<T> execute(List<?> facts, Class<T> type) throws Exception;
}

public class DefaultMethodExecutor implements MethodExecutor<Model1> {
    public List<Model1> execute(List<?> facts, Class<Model1> type) throws Exception
    {
       //...
    }
} 

If the element type of facts should be configurable for a specific implementation, you need to make that a parameter too.

public interface MethodExecutor<T, F> {
    List<T> execute(List<? extends F> facts, Class<T> type) throws Exception;
}
like image 63
Mark Peters Avatar answered Dec 31 '22 17:12

Mark Peters


You need to move your generic parameter types from method declaration to interface declaration, so you can parametrize specific implementations:

public interface MethodExecutor<T> {
    List<T> execute(List<?> facts, Class<T> type) throws Exception;
}

public class SpecificMetodExecutor implements MethodExecutor<Model1> {
    public List<Model1> execute(List<Model2> facts, Class<Model1> type) throws Exception {
        ...
    }
}
like image 35
hoaz Avatar answered Dec 31 '22 18:12

hoaz