Suppose I have interfaces as follows:
public interface UnaryFunction<Ret, Arg> {
public Ret invoke(Arg arg);
}
public interface BinaryFunction<Ret, Arg1, Arg2> {
public Ret invoke(Arg1 arg, Arg2 arg);
}
Now suppose I have a wrapper class like so:
public class ConstructorWrapper<Ret> {
// Wrapper for a java.lang.reflect.Constructor
private final Constructor<Ret> constructor;
// Try blocks in the following elided for brevity
// Trying to implement UnaryFunction<Ret, Arg> with this
public <Arg> Ret invoke(Arg arg) { return constructor.newInstance(arg); }
// Trying to implement BinaryFunction<Ret, Arg1, Arg2> with this
public <Arg1, Arg2> Ret invoke(Arg1 arg1, Arg2 arg2) { return constructor.newInstance(arg1, arg2); }
}
How do I change this so that ConstructorWrapper is declared to implement both UnaryFunction and BinaryFunction? Better yet, how do I make it so that passing in a one-argument constructor results in a ConstructorWrapper object (or subclass therein) that only implements UnaryFunction and passing in a two-argument constructor results in a ConstructorWrapper object that only implements BinaryFunction (ie. so you don’t pass in a unary constructor in a place where a BinaryFunction is expected)? Preferably with as little repetition as possible?
What is wrong with:
What is wrong with having a class provide both APIs?
If you don’t have both, make that two wrappers. They can have an abstract superclass if you want to reduce code duplication. But if you want type safety, the wrapper classes should implement the interfaces!