4

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?

2
  • 2
    For long snippets of code, please use the code button or indent 4 spaces. the tick mark is only used for code within text. Commented May 15, 2013 at 15:03
  • 2
    What exactly is the error of the compiler? Commented May 15, 2013 at 15:05

2 Answers 2

10

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;
}
Sign up to request clarification or add additional context in comments.

Comments

4

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 {
        ...
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.