ishan3243
ishan3243

Reputation: 1928

Method level generic return types in interfaces

Do method level generics in interfaces (for return types) ever make sense? Do they have any use? Example:-

public interface ABX { 
    public <T> T fx(String p);
}

I could simply make the generic class-level like so

public interface ABX<T> { 
    public T fx(String p);
}

Is there any situation at all where I would want the generic to be method-level in interfaces/abstract classes (for return types).

Upvotes: 0

Views: 628

Answers (1)

sisyphus
sisyphus

Reputation: 6392

Method level generics certainly do have utility. But you have to bind the generic type parameter somehow so typically such a method will have a generic argument, like Class, and then return a generic value. Your example doesn't do this, so it's difficult to see the value of the generic type parameter.

You can see examples of them all over the place - the ones I come across most are in the Jackson databinding class ObjectMapper - https://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/ObjectMapper.html, such as

<T> T readValue(InputStream is, Class<T> returnType)

So, the value here is that ObjectMapper is not a generically typed class but it allows me to bind any class (provided it can understand the class and how to set its various properties based on the input). The important point there is that you only need a single instance of ObjectMapper for an entire application, you don't need one for every type of object you might need to databind.

Upvotes: 2

Related Questions