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.