Search code examples
javagenericsbounded-wildcard

Bounded type as method parameter?


I am trying to enforce a particular subclass type on an abstract method, like so:

public abstract class Searcher {    
  public abstract SearchResult search(<T extends SearchInput> searchInput);
}

This is to ensure that subclasses of Searcher have to extend a corresponding subclass of SearchInput. I know I can use a bounded type for the method's return type, but I can't seem to get it to work as a method argument. Is this possible in Java?


Solution

  • Have a look at Java documentation on Generic Methods:

    The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.

    You need:

    public abstract class Searcher {
        public abstract <T extends SearchInput> SearchResult search(T searchInput);
    }
    

    Point is, that generic type declaration must happen before the signature part.