What is SuppressWarnings (“unchecked”) in Java?

前端 未结 11 591
轮回少年
轮回少年 2020-11-22 12:48

Sometime when looking through code, I see many methods specify an annotation:

@SuppressWarnings(\"unchecked\")

What does this mean?

11条回答
  •  无人及你
    2020-11-22 13:28

    Sometimes Java generics just doesn't let you do what you want to, and you need to effectively tell the compiler that what you're doing really will be legal at execution time.

    I usually find this a pain when I'm mocking a generic interface, but there are other examples too. It's usually worth trying to work out a way of avoiding the warning rather than suppressing it (the Java Generics FAQ helps here) but sometimes even if it is possible, it bends the code out of shape so much that suppressing the warning is neater. Always add an explanatory comment in that case!

    The same generics FAQ has several sections on this topic, starting with "What is an "unchecked" warning?" - it's well worth a read.

提交回复
热议问题