Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile type mismatch when using getClass() with some complicated Java generics

Tags:

java

generics

I have a method with this interface:

public <A extends Message, B extends Message> MessageConverter<A, B>
    getDefaultConverterFor(Class<A> inputClass, Class<B> outputClass);  

where the idea is that you have an Message of type A that you want to convert into an Message of type B, and you want to get a converter to do that from a repository of registered converters available. Unfortunately, I'm having huge trouble getting the types at either end of this to work as I expect.

More specifically, I'm trying to do this:

public <M extends Message> Message convert(M m)
{
    MessageConverter<M, DictMessage> converter = 
        getDefaultConverterFor(m.getClass(), DictMessage.class);

    return converter.convert(m);                
}

(i.e. take a message of any type and convert it into a DictMessage) but it gives me a compile error on the getDefaultConverter line:

Type mismatch: cannot convert from MessageConverter<capture#1-of ? extends Message,DictMessage> to MessageConverter<Message,DictMessage>".

I'm not even sure why this happens, let alone how to fix it. I'd imagine it's something to do with the class returned by getClass not quite matching up with M, but I don't really know. I could believe that it's possible that this is something that actually just doesn't work, but I can't think of any particular examples that break it... Thoughts?

like image 967
Tim Perry Avatar asked Jan 23 '26 12:01

Tim Perry


1 Answers

I have had a problem with Object.getClass() returning Class<?> for some time. The compiler doesn't know that m.getClass() is Class<M> but you can fix that with a cast.

@SuppressWarnings("unchecked")
MessageConverter<M, DictMessage> converter =
        getDefaultConverterFor((Class<M>) m.getClass(), DictMessage.class);
like image 131
Peter Lawrey Avatar answered Jan 26 '26 01:01

Peter Lawrey



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!