Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics Puzzler

I am trying to figure out how to get generics to jump through hoops.

I have:

interface Root { }
interface Middle extends Root { }
class Type implements Root { }

And many "Subtype" classes:

class Subtype1 extends Type implements Middle { }
class Subtype2 extends Type implements Middle { }
...

What I want is to declare a class with two type parameters T and S, where T is bound by Type and S is bound by T and Middle.

I can't see a way with generics to ensure that S extends T AND implements Middle. What I want is something like:

class Handler<T extends Root, S extends T, S extends Middle>;

or

class Handler<T extends Root, S extends <T extends Middle>>;

But of course neither are legal. Maybe there is some magic I am missing?

like image 995
Nick Palmer Avatar asked Mar 27 '13 23:03

Nick Palmer


1 Answers

Try introducing an abstract class that extends SubType and implements Middle, so its type can be used in Handler.

abstract class MiddleSubtype extends Subtype implements Middle { }

Then,

class Handler<T extends Root, S extends MiddleSubtype> {  //...

EDIT: Following the update to the question, the same idea would look like:

abstract class MiddleType extends Type implements Middle { }

class Subtype1 extends MiddleType { }
class Subtype2 extends MiddleType { }
...

class Handler<T extends Root, S extends MiddleType> {  //...
like image 87
rgettman Avatar answered Oct 20 '22 11:10

rgettman