Nick Palmer
Nick Palmer

Reputation: 2753

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?

Upvotes: 8

Views: 195

Answers (2)

janek
janek

Reputation: 184

Or you could make S generic itself:

interface SInt<A,B> {}
class Handler<T extends Root, S extends SInt<T, Middle>>{}

Upvotes: 0

rgettman
rgettman

Reputation: 178263

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> {  //...

Upvotes: 2

Related Questions