public class GenericsTest { // We have a generic type here that needs to return from its check method // a reference to the specialized type (that is, the generic's sub-class). static class Common<SelfType extends Common<SelfType,ElementType>,ElementType> { protected SelfType self() { return (SelfType) this; } public SelfType check( ElementType e ) { // do something here that is general to all sub-classes return self(); } // ... } static class Foo extends Common<Foo,Integer> { public Foo doFoo() { // do something here is is specific to Foos return this; } } static class Bar extends Common<Bar,String> { public Bar doBar() { // do something here is is specific to Bars return this; } } public static void main( String[] args ) throws Exception { Foo foo = new Foo(); Bar bar = new Bar(); foo.check(1).doFoo(); bar.check("a").doBar(); } } // END
Having a Java generic class return a type reference to its specialized class. Aka, using the self-type.
Emulating "self types" using Java Generics to simplify fluent API implementation is a very good example of how to more effectively use Java's generics and inheritance. The "self type" solution is something I would not have imagined. Further, it is motivating to see what other effects can be achieved through Java's generics. Read the article for a compete understanding of self types and a use of them. For those wishing to skip to the conclusion, if you need a generic class instance to return a typed reference to the specialized class then it is coded