Home » Java » What is SuppressWarnings (“unchecked”) in Java?

What is SuppressWarnings (“unchecked”) in Java?

Posted by: admin November 2, 2017 Leave a comment

Questions:

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

@SuppressWarnings("unchecked")

What does this mean?

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.

Questions:
Answers:

It is an annotation to suppress compile warnings about unchecked generic operations (not exceptions), such as casts. It essentially implies that the programmer did not wish to be notified about these which he is already aware of when compiling a particular bit of code.

You can read more on this specific annotation here:

SuppressWarnings

Additionally, Oracle provides some tutorial documentation on the usage of annotations here:

Annotations

As they put it,

“The ‘unchecked’ warning can occur when interfacing with legacy code written before the advent of generics (discussed in the lesson titled Generics).”

Questions:
Answers:

It could also mean that the current Java type system version isn’t good enough for your case. There were several JSR propositions / hacks to fix this: Type tokens, Super Type Tokens, Class.cast().

If you really need this supression, narrow it down as much as possible (e.g. don’t put it onto the class itself or onto a long method). An example:

public List<String> getALegacyListReversed() {
   @SuppressWarnings("unchecked") List<String> list =
       (List<String>)legacyLibrary.getStringList();

   Collections.reverse(list);
   return list;
}

Questions:
Answers:

The SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.

Questions:
Answers:

You can suppress the compiler warnings and tell the generics that the code which you had written is legal according to it.

Example:

@SuppressWarnings("unchecked")
public List<ReservationMealPlan> retreiveMealPlan() {
     List<ReservationMealPlan> list=new ArrayList<ReservationMealPlan>();
    TestMenuService testMenuService=new TestMenuService(em, this.selectedInstance);
    list = testMenuService.getMeal(reservationMealPlan);
    return list;
 }

Questions:
Answers:

Simply: It’s a warning by which the compiler indicates that it cannot ensure type safety.

JPA service method for example:

@SuppressWarnings("unchecked")
public List<User> findAllUsers(){
    Query query = entitymanager.createQuery("SELECT u FROM User u");
    return (List<User>)query.getResultList();
}

If I didn’n anotate the @SuppressWarnings(“unchecked”) here, it would have a problem with line, where I want to return my ResultList.

In shortcut type-safety means: A program is considered type-safe if it compiles without errors and warnings and does not raise any unexpected ClassCastException s at runtime.

I build on http://www.angelikalanger.com/GenericsFAQ/FAQSections/Fundamentals.html

Questions:
Answers:

One trick is to create an interface that extends a generic base interface…

public interface LoadFutures extends Map<UUID, Future<LoadResult>> {}

Then you can check it with instanceof before the cast…

Object obj = context.getAttribute(FUTURES);
if (!(obj instanceof LoadFutures)) {
    String format = "Servlet context attribute \"%s\" is not of type "
            + "LoadFutures. Its type is %s.";
    String msg = String.format(format, FUTURES, obj.getClass());
    throw new RuntimeException(msg);
}
return (LoadFutures) obj;

Questions:
Answers:

As far I know, for now it has to do with suppressing warnings about generics; generics are a new programming construct not supported in JDK versions earlier than JDK 5, so any mixes of the old constructs with the new ones might pose some unexpected results.

The compiler warns the programmer about it, but if the programmer already knows, they can turn those dreaded warnings off using SuppressWarnings.