What are the possibilities to design an API that n

2020-07-25 22:23发布

问题:

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

回答1:

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