• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Generics - Reference to container of generic type from that type  RSS feed

Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have recently stumbled upon the following problem when writing my library:
I have class A, which is supposed to be extended in the final application. For convenience of use the Collection that holds references to the objects of this class is defined in a generic way (Collection<T extends A>). I have also found it necessary to keep a reference to that Collection in every instance of A. (I took precautions to avoid memory leaks.) What type do I assign to that reference?

To be more specific, here's a tl;dr:
A Server object keeps references to all of its clients. Clients are represented by class ServerClient that is supposed to be extended when in use. In order to avoid tons of casting to address application-specific methods of ServerClient subclasses, I decided to make Server objects generic (Server<C extends ServerClient>), so that Server.getClients() returns an appropriate Collection. At the same time, while the client is connected to the server, I need to address the Server's fireDisconnectEvent(C client) (as an example) object from inside the ServerClient class or its subclasses, so I want to keep a reference to it. Here's where the problem lies: if I make the field of type Server<?>, it results in a ton of unsafe (from compiler's PoV) casting, as the input type becomes "?" otherwise. The ideal way to do it would be to make the type of the field something like Server<this.getClass()>, but it is obviously impossible.

Any ideas? Is it possible at all or is it easier to do the casting and complain about Java's generics? Maybe there is something I'm overseeing?
Thank you in advance.

P.S. The subject is a bit confusing, I guess. Just as the situation as a whole.
Saloon Keeper
Posts: 9378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a very strange setup. Why does the server's fire method require a C, and not a ServerClient?

If you really wanted to, you could keep a Server<? super MyClient> in your MyClient object, but I think you should probably work on a whole different design altogether.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!