Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is SuppressWarnings ("unchecked") in Java?

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

@SuppressWarnings("unchecked") 

What does this mean?

like image 679
jojo Avatar asked Jul 15 '09 06:07

jojo


People also ask

What does unchecked mean in Java?

An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.

What is SuppressWarnings annotation in Java?

Use of @SuppressWarnings is to suppress or ignore warnings coming from the compiler, i.e., the compiler will ignore warnings if any for that piece of code. 1. @SuppressWarnings("unchecked") public class Calculator { } - Here, it will ignore all unchecked warnings coming from that class.

What is SuppressWarnings ({ Rawtypes unchecked })?

If you choose to put @SuppressWarnings("rawtypes") at the method level, Eclipse will suppress all raw-types warnings inside that method. If we compile same code without @SuprressWarnings, using javac compiler it will show the following hint: $ javac RawType.

What is an unchecked cast in Java?

Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a nonqualified type or the other way around. E.g. this line. Set<String> set = new HashSet();


1 Answers

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.

like image 122
Jon Skeet Avatar answered Nov 16 '22 00:11

Jon Skeet