发出警告的正确步骤是:
- First and foremost, prove that the unchecked cast is safe, and document why
- Only then perform the unchecked cast, and annotate
@SuppressWarnings("unchecked")
on the variable declaration (not on the whole method)
类似情况:
// this cast is correct because...
@SuppressWarnings("unchecked")
GenericInterface<String> mockedInterface =
(GenericInterface<String>) EasyMock.createMock(GenericInterface.class);
Guidelines
摘录如下: 有效 Java 2nd Edition: 项目24: 消除未经检查的警告:
- Eliminate every unchecked warning that you can.
- If you can t eliminate a warning, and you can prove that the code that provoked the warning is typesafe, then (and only then) suppress the warning with
@SuppressWarning("unchecked")
annotation.
- Always use the
SuppressWarning
annotation on the smallest scope possible.
- Every time you use an
@SuppressWarning("unchecked")
annotation, add a comment saying why it s safe to do so.
Related questions
Refactoring the cast
在大多数情况下,还有可能在一种发电机中进行未加检查的投放。 它看着这样的情况:
static <E> Set<E> newSet(Class<? extends Set> klazz) {
try {
// cast is safe because newly instantiated set is empty
@SuppressWarnings("unchecked")
Set<E> set = (Set<E>) klazz.newInstance();
return set;
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
}
然后,在别处,你只能做:
// compiles fine with no unchecked cast warnings!
Set<String> names = newSet(HashSet.class);
Set<Integer> nums = newSet(TreeSet.class);
See also