How to avoid unchecked cast warnings with Java Generics

You're getting warnings because what you're doing can't be proved to be safe. You're assuming that getInstance(colTypeL) will return an Extractor<L> - but that can't be verified at either compile-time or execution time.

You can use @SuppressWarnings("unchecked") as mentioned by others, but I would try to rethink the design somewhat.


You can use the following annotation to make the compiler not output those warnings:

@SuppressWarnings("unchecked")

See this related question which deals with the same issue. The answer there will explain everything you need to know.


If you are using the Spring Framework, you can use CastUtils:

import static org.springframework.data.util.CastUtils.cast;
obj.setString(cast(someObject));
String bob = cast(someObject);