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

本文是小编为大家收集整理的关于设计一个需要根据通用类型进行重载的API有哪些可能性?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

在给定的类Example<A>中,我需要以下两个功能可用:

void doSomething(Supplier<A>)

<B> void doSomething(Supplier<B>)

实现这一目标的可能性是什么?我知道以下方法:

  1. 给出函数不同的名称
  2. 使用包装器型进行二维WrapperType.of(Supplier<B>)
  3. 使用将Example<A>转换为Example<B>
  4. 的函数

还有其他方法吗?

我不喜欢1)当它抓住我的API时. 2)实际上是冗长的,因为我必须经常称呼该功能,并且在测试代码外,静态导入非常不寻常. 3)对我不希望用户对

"关心"的内部问题非常明确

推荐答案

我通过指定Function<A,B>的扩展名来找到另一种方法:

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

可以定义Function<A,B>和SpecificFunction<A,C>上的多个过载,然后由于类型的擦除而没有其他类,这是不可能的.这是因为oracle.com/javase/specs/jls/se8/se8/html/jls-15.html#jls-15.12.5" rel=" rel=" rel="nortoflowllow norefollow norefollow norefloll规范明确强制执行Java编译器必须将函数调用绑定到它可以找到的最特定函数.排定如何找到最特定函数的一部分如下:如果两个函数m(a)和n(b)存在m(a),则比b不是b不是a的子类型. ,它适用于我们的SpecificFunction<A,B>.

本文地址:https://www.itbaoku.cn/post/1937843.html

问题描述

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

void doSomething(Supplier<A>)

<B> void doSomething(Supplier<B>)

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

  1. give the functions different names
  2. use a wrapper-type for the second-definition WrapperType.of(Supplier<B>)
  3. use a function that converts Example<A> to Example<B>

Are there any other approaches?

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

推荐答案

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

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

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>.