Misleading Java Generic Errors in Eclipse
An incompatibility between Java source versions in Eclipse made a generics error show up as:
Type mismatch: cannot convert from Object to ILocationService.
when it should really have read something like:
Type mismatch: return type of TypeLoader is generic – this project is not.
Here’s what happened to trigger this error.
The type TypeLoader contains a generic method with the following signature:
public static <T> T loadType( String name, Class<T> forType ) throws TypeLoaderException
My call – which was not in a generic project – looks like this:
ILocationService ls = TypeLoader.loadType( locationServiceClass, ILocationService.class );
Eclipse’s exception – Cannot convert from Object to ILocationService – is a bit misleading, since there is no cast there: the generic type parameter is defined by ILocationService.class which is of type Class<ILocationService>, and in fact the TypeLoader passes all its JUnit tests.
The solution was that I’d upated the master POM for the project containing the call, but not updated the project in Eclipse (using m2eclipse’s menu Maven > Update Project Configuration. Once I’d done this, m2eclipse updated the source version from 1.4 to 1.6 – and the exception went away.