Annotations   «Prev  Next»

Suppress Warnings safe varargs

We are going to add another Annotation above the main method. Within the
class JavaLangAnnotations {
We are going to add another Annotation above the main method.

@SuppressWarnings({"deprecation", "removal"})

SuppressWarnings and SafeVarargs

To understand the reasons for the @SafeVarArgs annotation, you have to understand the problem, which starts with some definitions.
  1. 1. A reifiable type is a type of one of the following: a) primitive, b) non-generic type, c) raw type or an invocation of a type with unbound wildcards. This is a type that loses no information during the type erasure process.
  2. 2. A non-reifiable type is a type who is type parameter information is lost by type erasure and includes invocations of generic types that are not defined as unbounded wildcards.
  3. 3. Heap pollution occurs when a variable of a parameterized type refers to an object that is not of that parameterized type.
  4. 4. In unchecked warning is generated if the correctness of an operation involving a parameterized type cannot be verified. This occurs if you mix raw types and parameterized types, or when performing unchecked casts.
  5. 5. Varargs - you will remember that varargs stands for variable arguments in a parameter of a method declaration. The varargs parameter is translated by the compiler into an array.
  6. 6. You need to also remember that you cannot create an array of parameterized types. You can however specify a varargs declaration with a parameterized type (non-reifable type).

SuppressWarnings and SafeVarargs

It is this discrepancy of being able to declare varargs with a parameterized type, and arrays having no support for parameterized types that leads to the possibility of heap pollution, since the varargs will get translated to a non-parameterized type array and not a parameterized type array.
Create a new class called SafeVarArgsExample We are making the array a reified type.
// Generic Array creation is not allowed
MyClass[] myArray = {
		new MyClass<>("Irmgard"),
		new MyClass<>("Bruno")
};

You use the @SafeVarargs annotation when you can safely assert that the implementation of the method will not throw a ClassCastException or other similar exception due to improper handling of the varargs formal parameter.
The @SafeVarargs annotation is a documented part of the method’s contract (it will be included in the Java docs API).
This annotation asserts that the implementation of the method will not improperly handle the varargs formal parameter. This annotation is considered more desirable than
@SuppressWarnings({“unchecked”,”varargs”});

We have covered all of the Java Annotations in the java.lang package.