根据泛型类型设计需要重载的 API 的可能性有哪些? [英] What are the possibilities to design an API that needs overloads depending on a generic type?

查看:19
本文介绍了根据泛型类型设计需要重载的 API 的可能性有哪些?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在给定的类 Example 我需要以下两个函数可用:

In a given class Example<A> I need the following two functions to be available:

void doSomething(Supplier)

<代码>void doSomething(Supplier)

实现这一目标的可能性有哪些?我知道以下方法:

What are the possibilities to achieve this? I know the following approaches:

  1. 给函数起不同的名字
  2. 使用包装器类型作为第二个定义 WrapperType.of(Supplier)
  3. 使用一个函数将Example转换为Example

还有其他方法吗?

我不喜欢 1),因为它使我的 API 变得混乱.2) 真的很冗长,因为我必须经常调用所说的函数,并且静态导入在测试代码之外非常不寻常.3)对内部问题非常明确,我不希望用户关心"

I dislike 1) as it clutters my API. 2) is really verbose as I have to call said function often and static imports are very unusual outside of testing code. 3) is very explicit about the internal problem which I don't want the user to 'care' about

推荐答案

通过指定Function 的扩展,我找到了另一种方法,如下所示:

I have found another way by specifying an extension of Function<A,B> as follows:

class SpecificFunction<A,B> extends Function<A,B> {}

FunctionSpecificFunction 上的多个重载然后可以定义,因为类型擦除,如果没有额外的类,这是不可能的.这是因为 java 语言规范明确强制java编译器必须将函数调用绑定到它可以找到的最具体的函数.如何找到最具体的函数的定义中的一部分如下:如果两个函数 m(a)n(b) 存在 m(a)n(b) 更具体,如果 b 不是 a 的子类型,这适用于我们的 特定函数.

Multiple overloads on Function<A,B> and SpecificFunction<A,C> can be defined then which would be impossible without an additional class because of type erasure. This works because the java language specification explicitly enforces that the java compiler has to bind a function call to the most specific function it can find. One part in the defnition of how to find the most specific function is as follows: if two functions m(a) and n(b) exists m(a) is more specific than n(b) if b is not a subtype of a, which holds for our SpecificFunction<A,B>.

这篇关于根据泛型类型设计需要重载的 API 的可能性有哪些?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆