Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!news-1.dfn.de!news.dfn.de!news.informatik.hu-berlin.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.java.programmer Subject: Re: can this be done with generics? Date: Mon, 25 Nov 2013 22:31:54 +0100 Lines: 71 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net BzILUzNJeVg9TlqtoLkx5w2lp7MntUXRLtZUt413YrDZJAq6o= Cancel-Lock: sha1:H7S7VULCm6Iik144B8NFE6GNOBM= User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Thunderbird/24.1.1 In-Reply-To: X-Antivirus: avast! (VPS 131125-1, 25.11.2013), Outbound message X-Antivirus-Status: Clean Xref: csiph.com comp.lang.java.programmer:26614 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> { 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>().foo().baz().bar(); new TheEnd().foo().last().baz().bar(); } } class Bar> extends Foo { public T bar() { System.out.println(getClass().getName() + " in bar()"); return self(); } } class Baz> extends Bar { public T baz() { System.out.println(getClass().getName() + " in baz()"); return self(); } } final class TheEnd extends Baz { 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/