<code>@SuppressWarnings</code> in Java
@SuppressWarnings tells the compiler to ignore specific warnings in the annotated element. Use it sparingly and at the smallest possible scope β a local variable or single method β not on a whole class.
Common warning keys
| Key | Meaning |
|---|---|
"unchecked" | Unchecked generic operation |
"rawtypes" | Use of raw generic types |
"deprecation" | Using @Deprecated API |
"unused" | Unused variable / parameter / import |
"serial" | Missing serialVersionUID |
"removal" | Using API marked forRemoval = true |
Narrow scope is right scope
public class OrderService {
public List<Order> all() {
@SuppressWarnings("unchecked") // β
just this one cast
List<Order> list = (List<Order>) legacyApi.fetch();
return list;
}
}
Multiple keys
@SuppressWarnings({"unchecked", "rawtypes"})
public void legacyCall() { ... }
Document the reason
// Legacy DAO returns a List with mixed types β safe because we only read strings.
@SuppressWarnings("unchecked")
List<String> rows = (List<String>) dao.query("SELECT name FROM users");
Class-level suppression β a smell
@SuppressWarnings("unchecked") // β hides genuine bugs elsewhere in the class
public class LegacyAdapter { ... }
If every method needs the suppression, there's a design problem. Narrow it down.
Don't suppress, fix
Before writing @SuppressWarnings, see whether you can fix the underlying issue:
- unchecked β parameterise the collection properly.
- rawtypes β add the type argument (
List<?>if you don't know). - deprecation β migrate to the replacement.
- unused β delete the variable.
Common mistakes
- Broad suppression on a class or package β masks new warnings.
- No comment β future readers won't know why it's there.
- Invalid key β compilers silently accept unknown keys. Typo = no effect. IDEs usually flag them.
Related
Pillar: Java annotations. See also @Deprecated.