Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I annotate with @SuppressWarnings("unchecked") for a single cast instead of a whole method?

It seems excessive when annotations apply to a method.

How do I use the annotation @SuppressWarnings("unchecked") for a single cast instead of a whole method?

In this example, I just finished checking that a cast will be safe and so I proceed to cast but I get an annoying warning.

@Override
public void execDetails()
{ 
    Map<Integer, ResponseList<?>> responseMap = 
            new HashMap<Integer, ResponseList<?>>();

    // ... omitted code ...

    ResponseList<?> responseList = responseMap.get(requestId);
    Class<?> elementType = responseList.getElementType();
    if (elementType == ExecutionDetail.class)
        ((ResponseList<ExecutionDetail>)responseList).add(new ExecutionDetail());

}
like image 266
H2ONaCl Avatar asked Nov 04 '11 13:11

H2ONaCl


People also ask

What is the use of @SuppressWarnings unchecked 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.

Which annotation should be used to remove warnings from a method?

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.

What is SuppressWarnings annotation in Java?

Annotation Type SuppressWarningsIndicates that the named compiler warnings should be suppressed in the annotated element (and in all program elements contained in the annotated element). Note that the set of warnings suppressed in a given element is a superset of the warnings suppressed in all containing elements.

What is @SuppressWarnings unlikely ARG type?

This implies that the compiler may show "unwanted" warnings, or filter out invocations that are in fact bugs. For the former case, @SuppressWarnings("unlikely-arg-type") will document the exception both for the user and for the compiler.


1 Answers

You can use @SuppressWarnings for a single variable declaration:

public static List<String> foo(List<?> list) {
    List<String> bad = (List<String>) list;

    @SuppressWarnings("unchecked")
    List<String> good = (List<String>) list;
    return good;
}

It has to be at the point of the local variable declaration though:

Annotations may be used as modifiers in any declaration, whether package (§7.4), class (§8), interface, field (§8.3, §9.3), method (§8.4, §9.4), parameter, constructor (§8.8), or local variable (§14.4).

like image 157
Jon Skeet Avatar answered Sep 30 '22 12:09

Jon Skeet