How to avoid unchecked cast warnings with Java Generics

前端 未结 3 1596
慢半拍i
慢半拍i 2020-12-06 16:40

Somehow my old question was closed, so I open a new one:

I am using Java Generics to implement a generic bidirectional Hash Map out of an SQL Query. It should be abl

相关标签:
3条回答
  • 2020-12-06 17:09

    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.

    0 讨论(0)
  • 2020-12-06 17:19

    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);
    
    0 讨论(0)
  • 2020-12-06 17:21

    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.

    0 讨论(0)
提交回复
热议问题