Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics: Require generic to be subclass of a certain type

Tags:

java

generics

I have an abstract generic class:

public abstract class AbstractMessageHandler<T extends AbstractMessageHandler>
{
    public abstract List<String> getTypesOfMessages();
    public abstract void handleMessage(String message, CometClient client);

    public T setResponseValues(AbstractMessage request, T response )
    {
        response.setCompanyId(request.getCompanyId());
        response.setMessageGroup(request.getMessageGroup());
        response.setUserId(request.getUserId());
        response.setTimeStamp(AbstractMessage.getCurrentTimeStamp());

        return response;
    }
}

I need the generic subclass to be a subclass of this class. In otherwords, the generic must be a subclass of AbstractMessageHandler. This however gives me compilation issues. Can anyone let me know what I am doing wrong?

Thanks

like image 676
user489041 Avatar asked Sep 27 '12 18:09

user489041


People also ask

Can a generic class be subclass of non-generic?

A generic class can extend a non-generic class.

How can we restrict generics to a subclass of particular class?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.

Can you define a generic method in a non-generic class in Java?

Yes, you can define a generic method in a non-generic class in Java.


1 Answers

You need to follow the example of the Enum class:

public abstract class AbstractMessageHandler<T extends AbstractMessageHandler<T>>
like image 99
jtahlborn Avatar answered Sep 20 '22 22:09

jtahlborn