Search code examples
javagenericsabstract-classgeneric-type-argument

Solve Java Generic Type Error with Abstract Class Method


I wants to achieve something like this in java, but getting compile time error:

The method onMessage(TextMessage, Class) in the type AbstractTestLoader is not applicable for the arguments (TextMessage, Class)

I understand the reason of that error, but I also feel there should be some way to achieve this with casting or may be some other way.

public abstract class AbstractTestLoader<T extends AbstractEntity<T>> {

    public void onMessage(TextMessage message) throws Exception {
        onMessage(message, this.getClass()); // I want to correct this line in such a way so that I can call below method with actual Class of {T extends AbstractEntity<T>}
    }

    public void onMessage(TextMessage message, Class<T> clazz) throws Exception {
        //here my original logic will go
    }
}

Solution

  • Finally, after couple of tries I just get simple and working solution, but still I am open to hear other best answers if possible. Thanks

    public abstract class AbstractTestLoader<T extends AbstractEntity<T>> {
    
        abstract Class<T> getEntityType();
    
        public void onMessage(TextMessage message) throws Exception {
            onMessage(message, getEntityType());
        }
    
        public void onMessage(TextMessage message, Class<T> clazz) throws Exception {
            //here my original logic will go
        }
    }