Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference 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 very sure how to expose my problem so I'll go with an example :

Example

My Connection object is responsible for sending and receiving a certain type of (subclass of) Message over the network (only reproducing the relevant parts here) :

public class Connection<M extends Message> {
    public void send(M mes) {
        ...
    }
}

My Message object is an abstract class superclassing all kinds of messages sent over the network.

public abstract class Message {
    private transient Connection<?> conn;

    public void send() {
        this.conn.send(this);
    }
}

Of course, I have several subclasses of Message.

Problem

My problem comes from the Connection<?> conn property of Message : in it's current state eclipse tells me that

The method send(capture#7-of ?) in the type Connection< capture#7-of ?> is not applicable for the arguments (Message)

What type parameter should I use for Connection so that it is compatible with any subclass of Message ?

What I tried

I tried declaring Message as :

public abstract class Message<M extends Message<M>> {
    private transient Connection<M> conn;
    ...
}

And then I would have :

public class MessageA extends Message<MessageA> {
    ...
}

as a subclass.

But this is a big hassle (I have a lot of generic classes using subclasses of Message as type parameters) and it doesn't seem to be the proper way to handle it.

like image 240
n6g7 Avatar asked Aug 30 '26 12:08

n6g7


1 Answers

Use Connection<Message>:

public abstract class Message {
    private transient Connection<Message> conn;
    ...
}
like image 137
Luiggi Mendoza Avatar answered Sep 01 '26 00:09

Luiggi Mendoza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!