0 likes | 18 Views
https://firstcode.school/annotations-in-java-with-example/
E N D
Annotations in Java with Example In this article, we will learn about annotations in Java with syntax and examples. Annotations in Java The annotations represent the metadata i.e attached with the class, interface, function, or fields to denote a few additional information. The Java compiler and the JVM use this information during processing. Annotations in Java provide added information that can be used as an alternative option for XML and Java marker interfaces.These are not a part of the Java program, yet they provide access to add metadata information into the course code. Java introduced the concept of annotations from JDK5. As mentioned earlier, annotations provide only supplemental details about a program. It does not affect the operation of the code they annotate. More on java annotations: ■ They start with the symbol ‘@’. ■ Annotations do not modify the action or executions of a compiled program like its classes, variables, constructors, interfaces, methods, and many more. ■ We cannot consider them as mere comments. This is because annotations change the method a compiler treats a program. Built-in Java annotations:
Before getting into custom or user-defined annotations, let us take a look at the built-in Java annotations. Some of the below-given annotations are applied to Java code and the rest are applied to other annotations. Built-in Java Annotations in Java code: ■ @Override ■ @SuppressWarnings ■ @Deprecated Built-in Java Annotations used in other annotations: ■ @Target ■ @Retention ■ @Inherited ■ @Documented Built-in Java Annotations Let us look at a brief description of the built-in annotations. 1. @Override: The @Override annotation makes sure that the subclass method overrides the parent class method. If this is not the case, it throws an error during compilation. It is easy to get rid of careless mistakes like spelling mistakes by marking the @Override annotation. It gives assurance that the method is overridden. Sample program to implement @Overrided annotation: class FirstCode{ void learnCourse(){ System.out.println("Learn Courses with FirstCode");
}} class FirstCode2 extends FirstCode{ @Override void learnCourse(){ System.out.println("Learn Java with FirstCode"); }} class FirstCodeMain{ public static void main(String args[]){ FirstCode fc = new FirstCode2(); fc.learnCourse(); } } Output: Compile Time Error 2. @SuppressWarnings: This annotation suppresses the warning that the compiler issues. Sample program to implement @SuppressWarning annotation: import java.util.*; class FirstCode{ @SuppressWarning("unchecked") public static void main(String args[]){ ArrayList al = new ArrayList();
al.add("Java"); al.add(C++); al.add("Python"); for(Object obj:al) System.out.println(obj); } } Output: Now no warning at compile time Once we remove the @SuppressWarning(“unchecked”) annotation, the compiler shows a warning due to the usage of non-generic collections. 3. @Deprecated: The @Deprecated annotation denotes that the particular method is deprecated, so the compiler prints the warning message. It also notifies the user that it may be eradicated in future versions. Therefore, it is good to avoid such methods. Sample program to implement @deprecated annotation: class FirstCode{ void course1(){ System.out.println("Learn Java with FirstCode"); } @Deprecated void course2(){
System.out.println("Learn C++ with FirstCode"); }} class FirstCodeMain{ public static void main(String args[]){ Firstcode fc = new FirstCode(); fc.course2(); } } Output: During compilation:Note: Test.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. During Runtime: Learn C++ with FirstCode 4. @Documented: It is a marker interface that informs a toll that an annotation is to be documented. As the annotations are not provided in the ‘Javadoc’ comments, the @Documented annotation takes care of it. It enables the tools like ‘Javadoc’ to include and process the annotation that is given in the document. 5. @Target: It is designed to use as an annotation to another annotation. @Target takes a parameter that is a constant from the ElementType enumeration. It denotes the type of declaration to which we can apply the annotation. The constants given in the below table are given with the type of the declaration to which it corresponds.
Target Constant Annotations that can be applied to ANNOTATION_TYPE Another annotation CONSTRUCTOR Constructor FIELD Field LOCAL_VARIABLE Local variable METHOD Method PACKAGE Package PARAMETER Parameter TYPE Class, Interface, or enumeration There is flexibility to mention one or more of these values in a @Targetannotation. In such a case, we can mention them in the braces-delimited list. Eg: To denote an annotation that applies only to the local variables and fields, we can mention the @Target annotation as given below: @Target({Element.Type.FIELD, ElementType.LOCAL_VARIABLE}) 6. @Retention Annotation This denotes where and how long the annotation is retent. This annotation can hold three values:
SOURCE: Annotations that are retained at the source level and ignored by the compiler. CLASS: Annotations that are retained at the source level and ignored by the JVM. RUNTIME: These annotations will be retained during the runtime. 7. @Inherited: The @Inherited annotation is a marker that is used to declare annotations. It has control over the annotations that are used in class declarations. @Inhertited causes the annotation for a superclass to be inherited by a subclass. Thus, when a request is made to the subclass and the annotation is absent in the superclass and annotated with @Inherited, then that annotation will be returned. @Inherited @interface FirstCode { } @interface FirstCode{ } class Superclass{} class Subclass extends Superclass{} Java User-defined annotation: User-defined annotations or custom annotations can annotate program elements. These elements include the variables, constructors, methods, etc. They are applied before the declaration of an element. Syntax: Declaration of a user-defined annotation: @interface NewAnnotation
Here, NewAnnotation is the name of the annotation. Rules to declare user-defined annotation 1. AnnotationName is an interface. 2. The parameter should not be related to the method declarations and throw errors. 3. Null values cannot be assigned to these parameters. But they can have default values. 4. And these default values are optional. 5. The return type of the method must be either primitive, string, enum, an array of the primitive, class name, or class name type. Types of Annotation in Java: The annotations are classified into five main types: 1. Marker Annotation 2. Single-value Annotation 3. Full Annotation 4. Type Annotation 5. Repeating Annotation 1. Marker Annotation:
This annotation is no method or any data. The only purpose of this annotation is to mark a declaration. As it has no members, simply determining if it is present or absent is enough. @Override and @Deprecated are examples for marker Annotation. Eg: @interface NewAnnotation{} 2. Single-value annotation: An annotation with just one method is known as a single-value annotation. It allows a shorthand form of assigning a value to a variable. All we need to do is, mention the value for the data member when we apply the annotation. We need not mention the name of the data member. But to use this shorthand, the name of the member should be a value. Snippet to implement single-value annotation: @interface NewAnnotation{ int value(); } Snippet to implement single-annotation with default value: @interface NewAnnotation{ int value() default 0; } Example to apply a single-value annotation: @NewAnnotation(value=5) 3. Full Annotation or Multi-value annotation:
It is the annotation that consists of multiple values, data members, names, and pairs. Snippet to implement full annotation: @interface NewAnnotation{ int value1(); String value2(); String value3(); } } Example to implement full annotation with default values: @interface NewAnnotation{ int value1() default 1; String value2() default ""; String value3() default "FirstCode"; } Snippet to implement multi-value annotation: @NewAnnotation(value1=5, value2="FirstCode",value3="Java") 4. Type Annotation: We can apply this annotation where a type is present. For example, we can annotate the return type of a method. These are stated annotated with @Target annotation. Sample program to implement type annotation:
import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.TYPE_USE) @interface TypeAnnoPgm{} public class FirstCode{ public static void main(String[] args) { @TypeAnnoPgm String string = "This string is annotated with a type annotation"; System.out.println(string); xyz(); } static @TypeAnnoPgm int xyz() { System.out.println("The return type of this function is annotated"); return 0; } } Output: This string is annotated with a type annotation The return type of this function is annotated 5. Repeating Annotations: As the name suggests, these annotations can be applied to the same item more than once. To make the annotation repeatable, we must annotate it with the @Repeatable annotation as defined in the java.lang.annotation package. The values in the field mention the contained type for the repeatable annotation. The contained
is mentioned as an annotation whose value field is an array of the repeatable annotation type. To make an annotation repeatable, we must first create the container annotation. And we must mention the annotation type as an argument to the @Repeatable annotation. Sample program to implement repeating annotations: import java.lang.annotation.Annotation; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; @Retention(RetentionPolicy.RUNTIME) @Repeatable(MyRepeatedAnnos.class) @interface Words { String word() default "FirstCode"; int value() default 0; } @Retention(RetentionPolicy.RUNTIME) // Container annotation creation @interface MyRepeatedAnnos { Words[] value();
} public class Main { @Words(word = "First Course = Java", value = 1) @Words(word = "Second Course = C++", value = 2) public static void newMethod() { Main obj = new Main(); try { Class c = obj.getClass(); Method m = c.getMethod("newMethod"); Annotation anno = m.getAnnotation(MyRepeatedAnnos.class); System.out.println(anno); } catch (NoSuchMethodException e) { System.out.println(e); } } public static void main(String[] args) { newMethod(); } } Output: @MyRepeatedAnnos(value={@Words(value=1, word=”First Course”), @Words(value=2, word=”Second Course”)})
Building annotations in a real-world scenario: In reality, a Java programmer only needs to apply the annotation. It is not the task of the programmer to create or access annotations. These tasks are performed by the implementation provider. On behalf of the annotation, the Java compiler or the JVM performs various extra operations too. Sample program to implement User-defined annotations: package source; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Documented @Retention(RetentionPolicy.RUNTIME) @ interface MyAnnotation //user-defined annotations { String Developer() default "Programmer1"; String Expirydate(); } // will be retained at runtime public class FirstCode { @MyAnnotation(Developer="Programmer1", Expirydate="01-12-2023")
void fun1() { System.out.println("Test method 1"); } @MyAnnotation(Developer="Progammer2", Expirydate="01-10-2024") void fun2() { System.out.println("Test method 2"); } public static void main(String args[]) { System.out.println("Learn Java with FirstCode"); } } Output: Learn Java with FirstCode Uses of Java Annotations: 1. Provides commands to the compiler: The built-in annotations help the programmers in giving various instructions to the compiler. For example, the @Override annotations instruct the compiler that the annotated method is overriding the method.
2. Compile-time instructors: It also provides compile-time instructions to the compiler that can be later used. The programmers can use these as software build tools to generate XML files, code, etc. 3. Run-time instructions: Defining annotations can also be helpful during runtime. We can access this using Java Reflection. Where can we implement Annotations in Java? We can implement annotations to classes, methods, fields, and interfaces in java. Example: @Override void newMethod(){} In this example, the annotation instructs the compiler that newMethod() is a method that overrides. This method overrides (newMethod()) of its superclass. Summary This was all about annotations in java. Hope you enjoyed the article.