Learnitweb

Predefined annotation types in Java

The predefined annotation types defined in java.lang are @Deprecated, @Override, @SuppressWarnings, @SafeVarargs and @FunctionalInterface.

@Deprecated

@Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation. When an element is deprecated, it should also be documented using the Javadoc @deprecated tag.

/**
 * @deprecated
 * explanation of why it was deprecated
 */
 @Deprecated
 static void deprecatedMethod() { }

@Override

@Override annotation informs the compiler that the element is meant to override an element declared in a superclass.

@Override 
void overriddenMethod() { }

While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override does not correctly override a method in one of its superclasses, the compiler generates an error.

@SuppressWarnings

@SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate. For example, if a deprecated method is used, compiler will generate a warning.

In the following code, deprecation warning will be suppressed.

@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
	object.deprecatedMethod();
}

The Java Language Specification lists two categories for compiler warning: deprecation and unchecked.

The unchecked warning can occur when working with legacy code written before the advent of generics.

To suppress multiple categories of warnings, you can use the following syntax:

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

@SafeVarargs

This annotation when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargs parameter. The use of this annotation suppresses unchecked warnings related to the varargs usage.

@FunctionalInterface

This annotation was introduced in Java 8. This annotation indicates that the type declaration is intended to be a functional interface.