How to avoid unchecked cast warnings with Java Generics

孤者浪人 提交于 2019-11-28 00:43:45
Jon Skeet

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.

Richard Walton

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!