I have couple of supplied interfaces
public interface Finder,T extends Item> {
public S find(S s, int a);
}
public interf
Since you can't change the interfaces, you have no choice but to do brute cast.
In a more general discussion, what we need here is "self type", we want to say that a method invocation foo.bar()
should return the static type of foo
. Usually self type is wanted for fluent API where the method should return foo
itself. In your case you want to return a new object.
In java there's no satisfactory answer for self type. One trick is through self referenced type paramter like Foo
, however it is very ugly, and it cannot really enforce that any subtype Bar
must be a Foo
. And the trick won't help in your case at all.
Another trick may work
public interface Stack {
> X getCopy();
}
here, the caller supplies the exact return type.
S stack = ....;
...
stack = s.getCopy();
// compiles, because X is inferred to be S
This trick helps to simplify call sites. However brute casts still exists, hidden in implementations of getCopy()
. This trick is dangerous and caller must know what it is doing. Personally I wouldn't do it; it's better for force caller to do the cast.