• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics - Bounded Parameterized Types  RSS feed

 
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

If I define a generic type such as this one:



The type parameter (A) that is used to instantiate an instance of this class must extend/implement all of the classes/interfaces listed after "extends". However, I would like to define a generic class whose type parameter must extend/implement (at least) one of these type. I thought it be possible to achieve this using the following syntax:



But apparently not....is it possible?

Cheers,
Dan
[ May 05, 2008: Message edited by: Dan Murphy ]
 
Ranch Hand
Posts: 375
Monad Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not really sure what are you trying to achieve, but maybe you can make Animal, Sleepable, Runnable, and Eatable extend/implement a AnimalAction interface, and declare the collection as AnimalActions<A extends AnimalAction >
(but I realize that this doesn't prevent somebody to extend/implement AnimalAction and NOT implement any of those interfaces)
[ May 05, 2008: Message edited by: Gabriel Claramunt ]
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Having just had a quick look at the Java Tutorials about Generics, I think the | operator cannot be used to separate generic parameters like that. At least, it wasn't mentioned in the Java Tutorial.
 
Dan Murphy
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Gabriel Claramunt:
Not really sure what are you trying to achieve


What I'm actually trying to do is define a generic type that can only be instantiated with one of the wrapper types (Integer, Boolean, Long, Short, etc.) or a String. As far as I can tell, there is no way to do this without resorting to reflection.
 
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How would you use that type parameter? That is, what would you want to do with a variable that has the declared type A?
 
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interfaces by their nature and design are AND creatures: you're an Animal AND Serializable.

The only way to check if something implements ONE (or more) of multiple interfaces is to check at runtime.

You could certainly define a marker interface or an annotation that said ItIsAn_A_B_or_C - but to make absolute sure, you'd need to check at runtime.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!