Can a Java function's parameter require optional interfaces?
There's unfortunately no way to create that kind of retroactive relationship between two unrelated types.
If you can change foo()
and its invocations, you could be able to make use of functional interfaces matching the signatures that you invoke inside foo
. I'm using IntSupplier
here, with corresponding lambda expressions using concrete implementations of A
and B
.
Say you have these implementations:
class AImpl implements A {
//implementation
}
class BImpl implements B {
//implementation
}
You can change foo
to something like:
public int foo(IntSupplier get, IntSupplier somethingElse) {
int ret = 0;
if (somethingElse != null) {
ret = somethingElse.getAsInt();
}
return ret + get.getAsInt();
}
And call it this way:
A a = new AImpl();
B b = new BImpl();
int result = this.foo(a::get, b::somethingelse);
The only way I can imagine is this:
public int foo(A p) {
return internal_foo(p);
}
public int foo(B p) {
return internal_foo(p);
}
private int internal_foo(Object p) {
if (p instanceof A) {
return ((A)p).get();
}
if (p instanceof B) {
B b = (B)p;
ret = b.somthingelse();
return ret + b.get();
}
throw new ClassCastException("Wrong type");
}