How do I refer to a subclass as a type parameter?
Is there a way to use a subclass of the current class as a type parameter for a generic class?
I'm not really sure how to expose my problem, so I'll give an example:
Example
My object Connection
is responsible for sending and receiving a specific type (subclass) Message
over the network (just to reproduce the relevant parts here):
public class Connection<M extends Message> {
public void send(M mes) {
...
}
}
My Message
object is a superclassical abstract class, all kinds of messages sent over the network.
public abstract class Message {
private transient Connection<?> conn;
public void send() {
this.conn.send(this);
}
}
I have several subclasses of course Message
.
Problem
My problem comes from the property Connection<?> conn
Message
: in it, the current state of eclipse is telling me that
Send (capture # 7-of?) Method of type Connection <capture # 7-of? > not applicable for arguments (Message)
What type of parameter should you use for Connection
so that it is compatible with any subclass Message
?
What i tried
I tried to declare Message
as:
public abstract class Message<M extends Message<M>> {
private transient Connection<M> conn;
...
}
And then I would:
public class MessageA extends Message<MessageA> {
...
}
as a subclass.
But this is a big problem (I have a lot of generic classes using subclasses Message
as type parameters) and it doesn't seem like the right way to handle this.
source to share
To get M
for conn.send()
, you need an abstract method that will provide you M
with which subclasses to override to provide.
public abstract class Message<M> {
abstract M getMessage();
private transient Connection<M> conn;
public void send() {
conn.send(getMessage());
}
}
public class MessageA extends Message<MessageA> {
MessageA getMessage() {
return this;
}
}
source to share