Search code examples
javaeclipsegenericsdesign-patternscommand-pattern

Command Pattern with Generic Return Type


I'm trying to implement the Command Pattern with a generic return type in Java.

After reviewing this answer on SO I created a Command class (interface) that looks like this:

public interface Command <T> {

    T execute(ArrayList<String> list, T type);
}

public class SearchResultsPage implements Command{

    @Override
    public <T extends List<ProductPOJO>>  T execute(ArrayList<String> list, T type) {

    List<ProductPOJO> productPOJOList = generatePOJOFromSearch(list);

    type.addAll(productPOJOList);

    return type;
    }
}

However, Eclipse keeps complaining that:

The method execute(ArrayList, T) of type SearchResultsPage must override or implement a supertype method

But when I click

Create execute() in supertype Command

Eclipse automatically generates the method T execute(ArrayList<String> list, T type); in Command class (i.e, exact same signature as what I created) yet the error message does not go away.

How can I fix this?

Thanks!


Solution

  • Your implementation of the execute method is incorrect. You've made the interface generic with the T type parameter, but you don't supply a type argument when implementing it in the concrete class SearchResultsPage. This means you've implemented the raw form of the interface. Instead, you've made the method itself generic, when it isn't generic in the interface.

    Move the declaration of T in the class method to the class itself.

    public class SearchResultsPage<T extends List<ProductPOJO>> implements Command<T> {
        @Override
        public T execute(ArrayList<String> list, T type) {
            // ...
        }
    }