Got a little puzzle for a true Java Generics specialist… 😉
Let’s say I have the following two interfaces:
interface Processor {
void process(Foo foo);
}
interface Foo {
Processor getProcessor();
}
and, for example, the following two implementing classes:
static class SomeProcessor implements Processor {
static final SomeProcessor INSTANCE = new SomeProcessor();
@Override
public void process(Foo foo) {
if (foo instanceof SomeFoo) { // <-- GET RID OF THIS ?
// process ((SomeFoo) foo)
}
}
}
class SomeFoo implements Foo {
@Override
public Processor getProcessor() {
return SomeProcessor.INSTANCE;
}
}
Is there some way to make the two interfaces generic in such a way that I don’t need the marked instanceof check in the process() function and still have the following construct work elsewhere in my code?
foo.getProcessor().process(foo);
(where, of course, I don’t know what subclass of Foo I’m dealing with)
In other words: I’m looking for a way to define a function in an object such that it can only return another object that processes the type of object that contained the function. Note: I’m not just talking about processing some least common denominator super-class of the object containing the function (above: Foo), but that object’s actual class (above: SomeFoo).
(This is nowhere near as trivial as it may sound unless I’m really being stupid right now…)
This is uglier than I thought. My take:
Now, the following will compile:
but
doesn’t, because the compiler can not know that actual type of the passed foo is a subtype of its type parameter, as somebody could write:
We can work around this by requiring the subtypes of foo to implement a conversion to their type parameter:
Now, we can write:
and invoke this with
To make it easy to use, I recommend moving the helper method into class Foo:
Update: I think newaccts updated answer shows a more elegant solution, as it does not need the recursive type bounds.