November 2nd, 2012

I’ve been doing a little development generify some Java classes to make them reusable across a couple of web applications and wanted to share this neat trick I learned along the way.

Method that returns an object of the same class and type arguments as the callee

I think this is a fairly common requirement for example when you have an object that replaces another.  A contrived example


class Magazine { 
    Magazine nextEdition;
    Magazine nextEdition()  { 
        return this.nextEdition; 
    } 
} 

For some reason you want to make this class generic by genre.


interface Genre {
}
class Magazine<G extends Genre> {
}

How do you ensure nextEdition() returns the same genre?  The answer is to add an additional generic type parameter that references itself


class Magazine<M extends Magazine<M, G>, G extends Genre> {
    M nextEdition; 
    M nextEdition()  { 
        return this.nextEdition; 
    }
}

Not obvious, a little verbose, but it works!

Comments are closed.