Understanding Annotations in Java
2012-12-18 09:28
295 查看
Introduction
This article discusses the way of creating annotations in Java. It also shows how to apply annotations to other declarations. Finally it discusses how to obtain annotation information at runtime using Reflection.Background
Annotation is a new feature introduced by J2SE 5 that allows programmers to embed additional information called metadata into a Java source file. Annotations do not alter the execution of a program but the information embedded using annotations can be used by various tools during development and deployment.Using the code
Creating an annotation is similar to creating an interface. But the annotation declaration is preceded by an@symbol. The annotation declaration itself is annotated with the
@Retentionannotation. The
@Retentionannotation is used to specify the retention policy, which can be
SOURCE,
CLASS, or
RUNTIME.
RetentionPolicy.SOURCEretains an annotation only in the source file and discards it during compilation.
RetentionPolicy.CLASSstores the annotation in the .class file but does not make it available during runtime.
RetentionPolicy.RUNTIMEstores the annotation in the .class file and also makes it available during runtime.
Collapse | Copy Code
// Specifying runtime retention policy @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation { String author(); // Annotation member String date(); // Annotation member }
An annotation cannot have the
extendsclause. However, annotations implicitly extend the
Annotationinterface. The body of an annotation consists of method declarations without body. These methods work like fields.
In the above example, I have created two members, author and date to represent information about the creator, and date of writing of the class and method.
Once an annotation is created, it can be applied to classes, methods, fields, parameters, enums, and so on. While applying an annotation to a declaration, you must provide values for its members as follows:
Collapse | Copy Code
// Applying annotation to the class @MyAnnotation(author="Azim",date="22/10/2011,23/10/2011") public class Test { // Applying annotation to the method @MyAnnotation(author="Azim",date="22/10/2011") public static void testMethod() { System.out.println("Welcome to Java"); System.out.println("This is an example of Annotations"); } public static void main(String args[]) { testMethod(); showAnnotations(); }
Annotations can be queried at runtime using Reflection as follows:
Collapse | Copy Code
public static void showAnnotations() // Function to show annotation information { Test test=new Test(); // Instantiating Test class try { Class c=test.getClass(); // Getting Class reference Method m=c.getMethod("testMethod"); // Getting Method reference // Getting Class annotation MyAnnotation annotation1= (MyAnnotation)c.getAnnotation(MyAnnotation.class); // Getting Method annotation MyAnnotation annotation2=m.getAnnotation(MyAnnotation.class); // Displaying annotation information System.out.println("Author of the class: "+annotation1.author()); // Displaying annotation information System.out.println("Date of Writing the class: "+annotation1.date()); // Displaying annotation information System.out.println("Author of the method: "+annotation2.author()); // Displaying annotation information System.out.println("Date of Writing the method: "+annotation2.date()); } catch(NoSuchMethodException ex) { System.out.println("Invalid Method..."+ex.getMessage()); } }
In the above code, I have queried annotations applied to the class
Testas well as the method
testMethod().
To obtain annotation information for the class, the following statement is used:
Collapse | Copy Code
MyAnnotation annotation1=(MyAnnotation)c.getAnnotation(MyAnnotation.class);
To obtain annotation information for the method, the following statement is used:
Collapse | Copy Code
MyAnnotation annotation2=m.getAnnotation(MyAnnotation.class);
The annotation information is printed by using annotation objects.
相关文章推荐
- How Do Annotations Work in Java?--转
- Type Annotations in Java 8: Tools and Opportunities
- Annotations in Tiger, Part 1: Add metadata to Java code
- Understanding reference in java
- Understanding How Graal Works - a Java JIT Compiler Written in Java
- Understanding transient variables in Java and how they are practically used in HashMap---reference
- 译 Programming with typesafe enums and annotations in Java 5
- java call oracle procudure setBoolean问题PLS-00306: wrong number or types of arguments in call to
- Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
- How to Read, Write XLSX File in Java - Apach POI Example---reference
- Exception in thread "main" java.lang.ClassCastException: $Proxy13
- JAAS最经典的文章:USER AUTHENTICATION AND AUTHORIZATION IN THE JAVA(TM) PLATFORM
- 《Java in Action 》
- [Java Concurrency in Practice]第六章 任务执行
- [LeetCode][Java] Search in Rotated Sorted Array II
- java.lang.UnsupportedClassVersionError: Bad version number in .class file
- Understanding Properties in C#
- How to convert char array to String in Java
- FFmpeg Understanding(4. How to compile and run testing files utilizing FFMPEG in VC?)
- Think in JAVA中“被检查的异常”的理解