简体   繁体   English

接口中的方法级别通用返回类型

[英]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). 在所有情况下,我都希望泛型在接口/抽象类(对于返回类型)中处于方法级别。

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. 但是您必须以某种方式绑定通用类型参数,因此通常这种方法将具有通用参数(如Class),然后返回通用值。 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 您到处都可以看到它们的示例-我遇到最多的是在Jackson数据绑定类ObjectMapper中-https: //fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson /databind/ObjectMapper.html ,例如

<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). 因此,这里的值是ObjectMapper 不是通用类型的类,但它允许我绑定任何类(只要它可以理解该类以及如何根据输入来设置其各种属性)。 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. 重要的一点是,对于整个应用程序,您只需要一个ObjectMapper实例,而对于可能需要进行数据绑定的每种类型的对象,则不需要一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM