Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!newsreader4.netcologne.de!news.netcologne.de!.POSTED!not-for-mail From: Patrick Roemer Newsgroups: comp.lang.java.programmer Subject: Re: can this be done with generics? Date: Tue, 26 Nov 2013 12:03:42 +0100 Organization: news.netcologne.de Lines: 44 Distribution: world Message-ID: References: NNTP-Posting-Host: xdsl-78-34-146-223.netcologne.de Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Trace: newsreader4.netcologne.de 1385463823 23136 78.34.146.223 (26 Nov 2013 11:03:43 GMT) X-Complaints-To: abuse@netcologne.de NNTP-Posting-Date: Tue, 26 Nov 2013 11:03:43 +0000 (UTC) User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.24) Gecko/20100411 Thunderbird/2.0.0.24 Mnenhy/0.7.6.0 In-Reply-To: Xref: csiph.com comp.lang.java.programmer:26623 Responding to Robert Klemme: > 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(); > } > > } Very nice. The cast just manifests an implicit assumption, so I think it's justified here. The wildcards are somewhat disconcerting - but certainly better than not having a general solution at all. :) Best regards, Patrick