Re: can this be done with generics?
On 25.11.2013 12:59, Patrick Roemer wrote:
Responding to Andreas Leitgeb:
Is there a way to use *generics* for the methods of class Foo such that
each foo#() returns the *static* type on which the compiler saw it
applied?
Just a naive attempt... Not sure if this matches your use case and
requirements - this will only work for a one-level hierarchy with an
abstract root class and will probably require some ugly gymnastics
inside the Foo method implementations:
The approach is all but naive. And it can actually be made to work with
deeper hierarchies in a type safe way. There is only a single
@SuppressWarnings("unchecked") here:
package inh;
public class Foo<T extends Foo<?>> {
public T foo() {
System.out.println(getClass().getName() + " in foo()");
return self();
}
@SuppressWarnings("unchecked")
protected final T self() {
return (T) this;
}
public static void main(String[] args) {
new Baz<Baz<?>>().foo().baz().bar();
new TheEnd().foo().last().baz().bar();
}
}
class Bar<T extends Bar<?>> extends Foo<T> {
public T bar() {
System.out.println(getClass().getName() + " in bar()");
return self();
}
}
class Baz<T extends Baz<?>> extends Bar<T> {
public T baz() {
System.out.println(getClass().getName() + " in baz()");
return self();
}
}
final class TheEnd extends Baz<TheEnd> {
public TheEnd last() {
System.out.println(getClass().getName() + " in last()");
return self();
}
}
A final class does not need a type parameter any more as it does not
need to propagate it.
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/