Java Annotations

LEELA S
2 min readMar 21, 2022

--

Annotations are used to provide supplemental information about a program.

  • Annotations starts with @
  • Annotation do not change the action of a compiled program
  • Annotations helps to associate metadata to the program elements.(i.e) instant varibale,method,constructor,class etc.
  • Annotations are basically used to provide additional information

Types of Annotations

  • Built in Annotations (General purpose annotations & meta annotations)
  • Custom Annotation

Built in Annotations

Java popularly defines seven built in annotations

Four are imported from java.lang.annotation:

  • @Retention,
  • @Documented,
  • @Target,
  • @Inherited.

Three are included in java.lang:

  • @Deprecated,
  • @Override,
  • @SuppressWarnings.

Example

1)@override

It is a marker annotation that can be used only on methods. A method annotated with @Override must override a method from a superclass.

Program

Output:

Moon girl

2) @Deprecated

  • It is a marker annotation. It indicates that a declaration is obsolete and has been replaced by a newer form
  • @deprecated tag is for documentation and @Deprecated annotation is for runtime reflection
  • @deprecated tag has higher priority than @Deprecated annotation when both are together used

Example

Output

Deprecatedtest display();

Categories of Annotations

1)Marker Annotations

  • The only purpose is to mark a declaration
  • @Override is an example of Marker Annotation.
  • Syntax: @TestAnnotations( )

2)Single value Annotations

  • These annotations contain only one member and allow a shorthand form of specifying the value of the member.
  • Syntax: @TestAnnotations(“testing”);

3)Full Annotations

  • These annotations consist of multiple data members, names, values, pairs
  • Syntax: @TestAnnotations(name=”Moon”,value=”…”)

4)Type Annotations

  • These annotations can be applied to any place where a type is being used. For example, we can annotate the return type of a method.
  • These are declared annotated with @Target annotation.

5)Repeating Annotations

  • These are the annotations that can be applied to a single item more than once.
  • For an annotation to be repeatable it must be annotated with the @Repeatable annotation, which is defined in the java.lang.annotation package

Custom Annotations

Java Custom annotations or Java User-defined annotations are easy to create and use. The @interface element is used to declare an annotation

Example:

@interface Myannotation{

}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

LEELA S
LEELA S

No responses yet

Write a response