Detailed explanation of @SuppressWarnings annotation usage

Reprinted from: https://blog.csdn.net/hunhun1122/article/details/72356228

Today, let's talk about the role of the @SuppressWarnings annotation.

The last annotation provided by J2SE is @SuppressWarnings. What this annotation does is give the compiler an instruction to silence certain warnings inside the annotated code element.

The @SuppressWarnings annotation allows you to selectively suppress warnings in specific pieces of code (ie, classes or methods). The idea is that when you see a warning, you'll investigate it, and if you're sure it's not the problem,

You can then add a @SuppressWarnings annotation so that you don't see the warning again. While it may sound like it will mask potential bugs, it will actually improve code security as it will prevent

You are indifferent to warnings - every warning you see will be worth noting.

The problem I often encounter is not knowing when to use what annotations of @SupressWarnings, so I did the following

使用:
@SuppressWarnings(“”)
@SuppressWarnings({})
@SuppressWarnings(value={})

When coding, we always find warnings that the following variables are not used:

The above code is compiled and can be run, but the "exclamation mark" in front of each line seriously hinders the breakpoint we can judge whether the line is set. Then we can add before the method 

@SuppressWarnings("unused") removes these "exclamation marks".

1. @SuppressWarings annotation

Role: used to suppress the compiler to generate warning messages.

Example 1 - suppressing single-type warnings:

 

  1. @SuppressWarnings("unchecked")  
  2. public void addItems(String item){  
  3.   @SuppressWarnings("rawtypes")  
  4.    List items = new ArrayList();  
  5.    items.add(item);  
  6. }  

Example 2 - Suppressing multiple types of warnings:

 

 

  1. @SuppressWarnings(value={"unchecked", "rawtypes"})  
  2. public void addItems(String item){  
  3.    List items = new ArrayList();  
  4.    items.add(item);  
  5. }  

Example 3 - suppress all types of warnings:

  1. @SuppressWarnings("all")  
  2. public void addItems(String item){  
  3.    List items = new ArrayList();  
  4.    items.add(item);  
  5. }  

2. Annotation goals

 

According  to the source code of @SuppressWarnings, its annotation targets are local variables of classes, fields, functions, function input parameters, constructors and functions.

 Instead, it is recommended that the annotation should be declared closest to where the warning occurs. 

2. Suppress warning keywords

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325767369&siteId=291194637