Pregunta

¿Cuál es la lista de nombres de advertencia válidos de @SuppressWarnings en Java?

El bit que se encuentra entre el (" ") en @SuppressWarnings (" ") .

¿Fue útil?

Solución

Depende de tu IDE o compilador.

Aquí hay una lista para Eclipse Galileo:

  
      
  • todos para suprimir todas las advertencias
  •   
  • boxeo para suprimir las advertencias relativas a las operaciones de boxeo / desempaquetado
  •   
  • cast para suprimir las advertencias relativas a las operaciones de conversión
  •   
  • dep-ann para suprimir las advertencias relativas a la anotación en desuso
  •   
  • desaprobación para suprimir las advertencias relativas a la desaprobación
  •   
  • paso a paso para suprimir las advertencias relativas a faltas de interrupción en el interruptor   declaraciones
  •   
  • finalmente para suprimir las advertencias relativas al bloqueo final que no   volver
  •   
  • ocultación para suprimir las advertencias relativas a los locales que ocultan la variable
  •   
  • interruptor incompleto para suprimir las advertencias relativas a las entradas faltantes   en una declaración de cambio (caso de enumeración)
  •   
  • nls para suprimir las advertencias relativas a los literales de cadena que no son nls
  •   
  • null para suprimir las advertencias relativas al análisis nulo
  •   
  • restricción para suprimir las advertencias relacionadas con el uso de desalentado o   referencias prohibidas
  •   
  • serie para suprimir las advertencias relativas a la falta de serialVersionUID   campo para una clase serializable
  •   
  • acceso estático para suprimir las advertencias relativas a la estática incorrecta.   acceso
  •   
  • acceso sintético para suprimir las advertencias relativas a no optimizadas   acceso desde las clases internas
  •   
  • sin marcar para suprimir las advertencias relativas a operaciones sin marcar
  •   
  • acceso de campo no calificado para suprimir las advertencias relativas al campo   acceso no calificado
  •   
  • no utilizado para suprimir las advertencias relativas al código no utilizado
  •   

Lista para Indigo agrega:

  
      
  • javadoc para suprimir las advertencias relativas a las advertencias de javadoc
  •   
  • rawtypes para suprimir las advertencias relativas al uso de tipos brutos
  •   
  • método estático para suprimir las advertencias relativas a los métodos que podrían declararse como estáticos
  •   
  • super para suprimir las advertencias relativas a anular un método sin súper invocaciones
  •   

Lista para Juno agrega:

  
      
  • recurso para suprimir las advertencias relativas al uso de los recursos del tipo Closeable
  •   
  • anulación de sincronización para suprimir las advertencias debido a la falta de sincronización al anular un método sincronizado
  •   

Kepler y Luna usan la misma lista de fichas que Juno ( list ).

Los demás serán similares pero variarán.

Otros consejos

Se permiten todos los valores (los valores no reconocidos se ignoran). La lista de reconocidos es específica del compilador.

En Los Tutoriales de Java sin marcar y desprecation se enumeran como las dos advertencias requeridas por la especificación del lenguaje Java, por lo tanto, deben ser válidas para todos los compiladores:

  

Cada advertencia del compilador pertenece a una categoría. La especificación del lenguaje Java enumera dos categorías: en desuso y sin marcar.

Las secciones específicas dentro de La especificación del lenguaje Java donde se definen no son coherentes en todas las versiones . En la Especificación de Java SE 8 deseleccionado y en desuso se enumeran como advertencias del compilador en las secciones 9.6.4.5. @SuppressWarnings y 9.6.4.6 @Deprecated , respectivamente.

Para el compilador de Sun, ejecutar javac -X proporciona una lista de todos los valores reconocidos por esa versión. Para 1.5.0_17, la lista parece ser:

  • todos
  • desaprobación
  • sin marcar
  • caída
  • ruta
  • serie
  • finalmente

The list is compiler specific. But here are the values supported in Eclipse:

  • allDeprecation deprecation even inside deprecated code
  • allJavadoc invalid or missing javadoc
  • assertIdentifier occurrence of assert used as identifier
  • boxing autoboxing conversion
  • charConcat when a char array is used in a string concatenation without being converted explicitly to a string
  • conditionAssign possible accidental boolean assignment
  • constructorName method with constructor name
  • dep-ann missing @Deprecated annotation
  • deprecation usage of deprecated type or member outside deprecated code
  • discouraged use of types matching a discouraged access rule
  • emptyBlock undocumented empty block
  • enumSwitch, incomplete-switch incomplete enum switch
  • fallthrough possible fall-through case
  • fieldHiding field hiding another variable
  • finalBound type parameter with final bound
  • finally finally block not completing normally
  • forbidden use of types matching a forbidden access rule
  • hiding macro for fieldHiding, localHiding, typeHiding and maskedCatchBlock
  • indirectStatic indirect reference to static member
  • intfAnnotation annotation type used as super interface
  • intfNonInherited interface non-inherited method compatibility
  • javadoc invalid javadoc
  • localHiding local variable hiding another variable
  • maskedCatchBlocks hidden catch block
  • nls non-nls string literals (lacking of tags //$NON-NLS-)
  • noEffectAssign assignment with no effect
  • null potential missing or redundant null check
  • nullDereference missing null check
  • over-ann missing @Override annotation
  • paramAssign assignment to a parameter
  • pkgDefaultMethod attempt to override package-default method
  • raw usage a of raw type (instead of a parametrized type)
  • semicolon unnecessary semicolon or empty statement
  • serial missing serialVersionUID
  • specialParamHiding constructor or setter parameter hiding another field
  • static-access macro for indirectStatic and staticReceiver
  • staticReceiver if a non static receiver is used to get a static field or call a static method
  • super overriding a method without making a super invocation
  • suppress enable @SuppressWarnings
  • syntheticAccess, synthetic-access when performing synthetic access for innerclass
  • tasks enable support for tasks tags in source code
  • typeHiding type parameter hiding another type
  • unchecked unchecked type operation
  • unnecessaryElse unnecessary else clause
  • unqualified-field-access, unqualifiedField unqualified reference to field
  • unused macro for unusedArgument, unusedImport, unusedLabel, unusedLocal, unusedPrivate and unusedThrown
  • unusedArgument unused method argument
  • unusedImport unused import reference
  • unusedLabel unused label
  • unusedLocal unused local variable
  • unusedPrivate unused private member declaration
  • unusedThrown unused declared thrown exception
  • uselessTypeCheck unnecessary cast/instanceof operation
  • varargsCast varargs argument need explicit cast
  • warningToken unhandled warning token in @SuppressWarnings

Sun JDK (1.6) has a shorter list of supported warnings:

  • deprecation Check for use of depreciated items.
  • unchecked Give more detail for unchecked conversion warnings that are mandated by the Java Language Specification.
  • serial Warn about missing serialVersionUID definitions on serializable classes.
  • finally Warn about finally clauses that cannot complete normally.
  • fallthrough Check switch blocks for fall-through cases and provide a warning message for any that are found.
  • path Check for a nonexistent path in environment paths (such as classpath).

The latest available javac (1.6.0_13) for mac have the following supported warnings

  • all
  • cast
  • deprecation
  • divzero
  • empty
  • unchecked
  • fallthrough
  • path
  • serial
  • finally
  • overrides

A new favorite for me is @SuppressWarnings("WeakerAccess") in IntelliJ, which keeps it from complaining when it thinks you should have a weaker access modifier than you are using. We have to have public access for some methods to support testing, and the @VisibleForTesting annotation doesn't prevent the warnings.

ETA: "Anonymous" commented, on the page @MattCampbell linked to, the following incredibly useful note:

You shouldn't need to use this list for the purpose you are describing. IntelliJ will add those SuppressWarnings for you automatically if you ask it to. It has been capable of doing this for as many releases back as I remember.

Just go to the location where you have the warning and type Alt-Enter (or select it in the Inspections list if you are seeing it there). When the menu comes up, showing the warning and offering to fix it for you (e.g. if the warning is "Method may be static" then "make static" is IntellJ's offer to fix it for you), instead of selecting "enter", just use the right arrow button to access the submenu, which will have options like "Edit inspection profile setting" and so forth. At the bottom of this list will be options like "Suppress all inspections for class", "Suppress for class", "Suppress for method", and occasionally "Suppress for statement". You probably want whichever one of these appears last on the list. Selecting one of these will add a @SuppressWarnings annotation (or comment in some cases) to your code suppressing the warning in question. You won't need to guess at which annotation to add, because IntelliJ will choose based on the warning you selected.

And this seems to be a much more complete list, where I found some warnings specific to Android-Studio that I couldn't find elsewhere (e.g. SynchronizeOnNonFinalField)

https://jazzy.id.au/2008/10/30/list_of_suppresswarnings_arguments.html

Oh, now SO's guidelines contraddict SO's restrictions. On one hand, I am supposed to copy the list rather than providing only the link. But on the other hand, this would exceed the maximum allowed number of characters. So let's just hope the link won't break.

JSL 1.7

The Oracle documentation mentions:

  • unchecked: Unchecked warnings are identified by the string "unchecked".
  • deprecation: A Java compiler must produce a deprecation warning when a type, method, field, or constructor whose declaration is annotated with the annotation @Deprecated is used (i.e. overridden, invoked, or referenced by name), unless: [...] The use is within an entity that is annotated to suppress the warning with the annotation @SuppressWarnings("deprecation"); or

It then explains that implementations can add and document their own:

Compiler vendors should document the warning names they support in conjunction with this annotation type. Vendors are encouraged to cooperate to ensure that the same names work across multiple compilers.

I just want to add that there is a master list of IntelliJ suppress parameters at: https://gist.github.com/vegaasen/157fbc6dce8545b7f12c

It looks fairly comprehensive. Partial:

Warning Description - Warning Name

"Magic character" MagicCharacter 
"Magic number" MagicNumber 
'Comparator.compare()' method does not use parameter ComparatorMethodParameterNotUsed 
'Connection.prepare*()' call with non-constant string JDBCPrepareStatementWithNonConstantString 
'Iterator.hasNext()' which calls 'next()' IteratorHasNextCallsIteratorNext 
'Iterator.next()' which can't throw 'NoSuchElementException' IteratorNextCanNotThrowNoSuchElementException 
'Statement.execute()' call with non-constant string JDBCExecuteWithNonConstantString 
'String.equals("")' StringEqualsEmptyString 
'StringBuffer' may be 'StringBuilder' (JDK 5.0 only) StringBufferMayBeStringBuilder 
'StringBuffer.toString()' in concatenation StringBufferToStringInConcatenation 
'assert' statement AssertStatement 
'assertEquals()' between objects of inconvertible types AssertEqualsBetweenInconvertibleTypes 
'await()' not in loop AwaitNotInLoop 
'await()' without corresponding 'signal()' AwaitWithoutCorrespondingSignal 
'break' statement BreakStatement 
'break' statement with label BreakStatementWithLabel 
'catch' generic class CatchGenericClass 
'clone()' does not call 'super.clone()' CloneDoesntCallSuperClone

I noticed that //noinspection can be auto-generated in IntelliJ

  • make sure you have not already a plan @SuppressWarninigs before the statement
  • Now you can auto-generate the specific //noinspection by hitting Alt+Enter when you have the warning selected and then use the right arrow key to see the Suppress for ... option

Ended up here when I wanted to suppress a "switch has too few case labels" warning from IntelliJ. I did not find a complete List for IntelliJ's @SuppressWarning support but //noinspection did the trick for me.

If you're using SonarLint, try above the method or class the whole squid string: @SuppressWarnings("squid:S1172")

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top