SlideShare a Scribd company logo
1 of 18
Java Annotations
History
     The Java platform has had various ad-hoc annotation
mechanisms—for example, the transient modifier, or the
@deprecated javadoc tag.
     The general purpose annotation (also known as metadata)
facility was introduced to the Java Community Process as JSR-175
in 2002 and approved in September 2004.
     Annotations became available in the language itself beginning
with version 1.5 of the JDK. A provisional interface for compile-
time annotation processing was provided by the apt tool in JDK
version 1.5, and was formalized through JSR-269 and integrated
into the javac compiler in version 1.6.
What is it
     Annotations do not directly affect program semantics, but they
do affect the way programs are treated by tools and libraries, which
can in turn affect the semantics of the running program.
Annotations can be read from source files, class files, or
reflectively at run time.
     Annotations complement javadoc tags. In general, if the
markup is intended to affect or produce documentation, it should
probably be a javadoc tag; otherwise, it should be an annotation.
Built-In Annotations applied
to java code
@Deprecated—the @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, as shown in the following example. The use of the
"@" symbol in both Javadoc comments and in annotations is not coincidental —
they are related conceptually. Also, note that the Javadoc tag starts with a
lowercase "d" and the annotation starts with an uppercase "D".

 /**
   * @deprecated
   * explanation of why it was deprecated
   */
  @Deprecated
  static void deprecatedMethod() { }
Built-In Annotations applied
to java code
@Override—the @Override annotation informs the compiler that
the element is meant to override an element declared in a
superclass). While it's not required to use this annotation when
overriding a method, it helps to prevent errors. If a method marked
with @Override fails to correctly override a method in one of its
superclasses, the compiler generates an error.

 // mark method as a superclass method
  // that has been overridden
  @Override
  int overriddenMethod() { }
Built-In Annotations applied
to java code
@SuppressWarnings—the @SuppressWarnings annotation tells the compiler to
suppress specific warnings that it would otherwise generate.
// use a deprecated method and tell compiler not to generate a
warning@SuppressWarnings("all", "deprecation", "unchecked",
"fallthrough", "path", "serial", "finally")
In the example below, a deprecated method is used and the compiler would
normally generate a warning. In this case, however, the annotation causes the
warning to be suppressed.
 // use a deprecated method and tell
 // compiler not to generate a warning
 @SuppressWarnings("deprecation")
 void useDeprecatedMethod() {
    // deprecation warning - suppressed
    objectOne.deprecatedMethod();
 }
Built-In Annotations applied
to other annotations
•   @Target - Marks another annotation to restrict what kind of
    java elements the annotation may be applied to.
•   @Retention - Specifies how the marked annotation is stored --
    Whether in code only, compiled into the class, or available at
    runtime through reflection.
•   @Documented - Marks another annotation for inclusion in the
    documentation.
•   @Inherited - Marks another annotation to be inherited to
    subclasses of annotated class (by default annotations are not
    inherited to subclasses).
@Target
 You can specify a single target using a single value or multiple
ones using an array.

@Target ({
ElementType.PACKAGE,
ElementType.TYPE,
ElementType.CONSTRUCTOR,
ElementType.METHOD,
ElementType.PARAMETER,
ElementType.FIELD,
ElementType.LOCAL_VARIABLE,
ElementType.ANNOTATION_TYPE
})
@RetentionPolicy
•   RetentionPolicy.SOURCE retains an annotation only in
    the source file and discards it during compilation.
•   RetentionPolicy.CLASS stores the annotation in the .class
    file but does not make it available during runtime.
•   RetentionPolicy.RUNTIME stores the annotation in the
    .class file and also makes it available during runtime.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TryThis {
 String [] value();
}
Annotation attributes
Return types are restricted to primitives, String, Class, enums, annotations, and
arrays of the preceding types. Methods can have default values.
Here is an example annotation type declaration:

/**
 * Describes the Request-For-Enhancement(RFE) that led
 * to the presence of the annotated API element.
 */
public @interface RequestForEnhancement {
   int id();
   String synopsis();
   String engineer() default "[unassigned]";
   String date(); default "[unimplemented]";
  String[] text();
}
RetentionPolicy (CLASS vs
RUNTIME)
RUNTIME: Annotations are to be recorded in the class file by the compiler and
retained by the VM at run time, so they may be read reflectively.
CLASS: Annotations are to be recorded in the class file by the compiler but need
not be retained by the VM at run time.

skaffman (TM)
In practice, I'm not aware of any use-cases for CLASS. It would only be useful if
you wanted to read the bytecode programmatically, as opposed to via the
classloader API, but that's a very specialised case, and I don't know why you
wouldn't just use RUNTIME.
Ironically, CLASS is the default behaviour.
RetentionPolicy.SOURCE

These annotations don't make any sense after the compile has
completed, so they aren't written to the bytecode.

Example: @Override, @SuppressWarnings
RetentionPolicy.CLASS

It would only be useful if you wanted to read the bytecode
programmatically.
Annotation-based test
framework
To tie it all together, we'll build a simple annotation-based test
framework. First we need a marker annotation type to indicate that a
method is a test method, and should be run by the testing tool:

import java.lang.annotation.*;
/**
 * Indicates that the annotated method is a test method.
 * This annotation should be used only on parameterless static methods.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }
Annotation-based test
               framework
    Note that the annotation type declaration is itself
annotated. Such annotations are called meta-annotations.
    The first (@Retention(RetentionPolicy.RUNTIME))
indicates that annotations with this type are to be retained by
the VM so they can be read reflectively at run-time.
    The second (@Target(ElementType.METHOD))
indicates that this annotation type can be used to annotate
only method declarations.
Annotation-based test
             framework
   Here is a sample program, some of whose methods are
annotated with the above interface:
   public class Foo {
   @Test public static void m1() { }
     public static void m2() { }
   @Test public static void m3() { }
     public static void m4() { }
   @Test public static void m5() { }
   }
Annotation-based test
                   framework
import java.lang.reflect.*;
public class RunTests {
  public static void main(String[] args) throws Exception {
    int passed = 0, failed = 0;
    for (Method m : Class.forName(args[0]).getMethods()) {
      if (m.isAnnotationPresent(Test.class)) {
         try {
           m.invoke(null);
           passed++;
         } catch (Throwable ex) {
           System.out.printf("Test %s failed: %s %n", m, ex.getCause());
           failed++;
         }
      }
    }
    System.out.printf("Passed: %d, Failed %d%n", passed, failed);
  }
Understanding Annotations in Java

More Related Content

What's hot

Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
Ganesh Samarthyam
 
Java annotations
Java annotationsJava annotations
Java annotations
Sujit Kumar
 

What's hot (20)

Java features
Java featuresJava features
Java features
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Bt0074 oops with java
Bt0074 oops with javaBt0074 oops with java
Bt0074 oops with java
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
The Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.NetThe Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.Net
 
Java Basics
Java BasicsJava Basics
Java Basics
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java annotations
Java annotationsJava annotations
Java annotations
 
Java basic
Java basicJava basic
Java basic
 
Core java
Core javaCore java
Core java
 
Java se 8 fundamentals
Java se 8 fundamentalsJava se 8 fundamentals
Java se 8 fundamentals
 
PHP 5
PHP 5PHP 5
PHP 5
 
Getting Program Input
Getting Program Input Getting Program Input
Getting Program Input
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java programming(unit 1)
Java programming(unit 1)Java programming(unit 1)
Java programming(unit 1)
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for Productivity
 
java programming - applets
java programming - appletsjava programming - applets
java programming - applets
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMUAutomated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
 
Interface java
Interface java Interface java
Interface java
 

Viewers also liked

Viewers also liked (20)

Interactive web prototyping
Interactive web prototypingInteractive web prototyping
Interactive web prototyping
 
Java Generics: What it is and How to Implement it
Java Generics: What it is and How to Implement itJava Generics: What it is and How to Implement it
Java Generics: What it is and How to Implement it
 
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
 
User Behavior: Interacting With Important Website Elements
User Behavior: Interacting With Important Website ElementsUser Behavior: Interacting With Important Website Elements
User Behavior: Interacting With Important Website Elements
 
non-blocking java script
non-blocking java scriptnon-blocking java script
non-blocking java script
 
Unexpected achievements 2013
Unexpected achievements 2013Unexpected achievements 2013
Unexpected achievements 2013
 
External Widgets Performance
External Widgets PerformanceExternal Widgets Performance
External Widgets Performance
 
Getting to know magento
Getting to know magentoGetting to know magento
Getting to know magento
 
Quick Intro to Clean Coding
Quick Intro to Clean CodingQuick Intro to Clean Coding
Quick Intro to Clean Coding
 
Эффективный JavaScript - IQLab Frontend Fusion 2012
Эффективный  JavaScript - IQLab Frontend Fusion 2012Эффективный  JavaScript - IQLab Frontend Fusion 2012
Эффективный JavaScript - IQLab Frontend Fusion 2012
 
All things php
All things phpAll things php
All things php
 
Databases on Client Side
Databases on Client SideDatabases on Client Side
Databases on Client Side
 
Developing for e commerce is important
Developing for e commerce is importantDeveloping for e commerce is important
Developing for e commerce is important
 
Java serialization
Java serializationJava serialization
Java serialization
 
Manifest of modern engineers
Manifest of modern engineersManifest of modern engineers
Manifest of modern engineers
 
IGears: Template Architecture and Principles
IGears: Template Architecture and PrinciplesIGears: Template Architecture and Principles
IGears: Template Architecture and Principles
 
QA evolution to the present day
QA evolution to the present dayQA evolution to the present day
QA evolution to the present day
 
User focused design
User focused designUser focused design
User focused design
 
Seo and Marketing Requirements in Web Architecture
Seo and Marketing Requirements in Web ArchitectureSeo and Marketing Requirements in Web Architecture
Seo and Marketing Requirements in Web Architecture
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 

Similar to Understanding Annotations in Java

imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
i i
 

Similar to Understanding Annotations in Java (20)

Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
Junit4.0
Junit4.0Junit4.0
Junit4.0
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 
01slide
01slide01slide
01slide
 
01slide
01slide01slide
01slide
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
 
Java notes
Java notesJava notes
Java notes
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Unit of competency
Unit of competencyUnit of competency
Unit of competency
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2
 
Basics of java 1
Basics of java 1Basics of java 1
Basics of java 1
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 

More from Ecommerce Solution Provider SysIQ

Правила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработкеПравила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработке
Ecommerce Solution Provider SysIQ
 

More from Ecommerce Solution Provider SysIQ (13)

Developing for e commerce is important
Developing for e commerce is importantDeveloping for e commerce is important
Developing for e commerce is important
 
Magento code audit
Magento code auditMagento code audit
Magento code audit
 
Scalability and performance for e commerce
Scalability and performance for e commerceScalability and performance for e commerce
Scalability and performance for e commerce
 
Lupan big enterprise ecommerce fusion 2013
Lupan   big enterprise ecommerce fusion 2013Lupan   big enterprise ecommerce fusion 2013
Lupan big enterprise ecommerce fusion 2013
 
Going global
Going globalGoing global
Going global
 
Going Global
Going GlobalGoing Global
Going Global
 
QA evolution, in pictures
QA evolution, in picturesQA evolution, in pictures
QA evolution, in pictures
 
Management and Communications (IPAA)
Management and Communications (IPAA)Management and Communications (IPAA)
Management and Communications (IPAA)
 
Speed Up Your Website
Speed Up Your WebsiteSpeed Up Your Website
Speed Up Your Website
 
Testing schools overview
Testing schools overviewTesting schools overview
Testing schools overview
 
Модульные сетки в реальном мире
Модульные сетки в реальном миреМодульные сетки в реальном мире
Модульные сетки в реальном мире
 
Правила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработкеПравила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработке
 
Frontend Servers and NGINX: What, Where and How
Frontend Servers and NGINX: What, Where and HowFrontend Servers and NGINX: What, Where and How
Frontend Servers and NGINX: What, Where and How
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Recently uploaded (20)

psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 

Understanding Annotations in Java

  • 2. History The Java platform has had various ad-hoc annotation mechanisms—for example, the transient modifier, or the @deprecated javadoc tag. The general purpose annotation (also known as metadata) facility was introduced to the Java Community Process as JSR-175 in 2002 and approved in September 2004. Annotations became available in the language itself beginning with version 1.5 of the JDK. A provisional interface for compile- time annotation processing was provided by the apt tool in JDK version 1.5, and was formalized through JSR-269 and integrated into the javac compiler in version 1.6.
  • 3. What is it Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time. Annotations complement javadoc tags. In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.
  • 4. Built-In Annotations applied to java code @Deprecated—the @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, as shown in the following example. The use of the "@" symbol in both Javadoc comments and in annotations is not coincidental — they are related conceptually. Also, note that the Javadoc tag starts with a lowercase "d" and the annotation starts with an uppercase "D". /** * @deprecated * explanation of why it was deprecated */ @Deprecated static void deprecatedMethod() { }
  • 5. Built-In Annotations applied to java code @Override—the @Override annotation informs the compiler that the element is meant to override an element declared in a superclass). While it's not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error. // mark method as a superclass method // that has been overridden @Override int overriddenMethod() { }
  • 6. Built-In Annotations applied to java code @SuppressWarnings—the @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate. // use a deprecated method and tell compiler not to generate a warning@SuppressWarnings("all", "deprecation", "unchecked", "fallthrough", "path", "serial", "finally") In the example below, a deprecated method is used and the compiler would normally generate a warning. In this case, however, the annotation causes the warning to be suppressed. // use a deprecated method and tell // compiler not to generate a warning @SuppressWarnings("deprecation") void useDeprecatedMethod() { // deprecation warning - suppressed objectOne.deprecatedMethod(); }
  • 7. Built-In Annotations applied to other annotations • @Target - Marks another annotation to restrict what kind of java elements the annotation may be applied to. • @Retention - Specifies how the marked annotation is stored -- Whether in code only, compiled into the class, or available at runtime through reflection. • @Documented - Marks another annotation for inclusion in the documentation. • @Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses).
  • 8. @Target You can specify a single target using a single value or multiple ones using an array. @Target ({ ElementType.PACKAGE, ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.ANNOTATION_TYPE })
  • 9. @RetentionPolicy • RetentionPolicy.SOURCE retains an annotation only in the source file and discards it during compilation. • RetentionPolicy.CLASS stores the annotation in the .class file but does not make it available during runtime. • RetentionPolicy.RUNTIME stores the annotation in the .class file and also makes it available during runtime. @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface TryThis { String [] value(); }
  • 10. Annotation attributes Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. Methods can have default values. Here is an example annotation type declaration: /** * Describes the Request-For-Enhancement(RFE) that led * to the presence of the annotated API element. */ public @interface RequestForEnhancement { int id(); String synopsis(); String engineer() default "[unassigned]"; String date(); default "[unimplemented]"; String[] text(); }
  • 11. RetentionPolicy (CLASS vs RUNTIME) RUNTIME: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively. CLASS: Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time. skaffman (TM) In practice, I'm not aware of any use-cases for CLASS. It would only be useful if you wanted to read the bytecode programmatically, as opposed to via the classloader API, but that's a very specialised case, and I don't know why you wouldn't just use RUNTIME. Ironically, CLASS is the default behaviour.
  • 12. RetentionPolicy.SOURCE These annotations don't make any sense after the compile has completed, so they aren't written to the bytecode. Example: @Override, @SuppressWarnings
  • 13. RetentionPolicy.CLASS It would only be useful if you wanted to read the bytecode programmatically.
  • 14. Annotation-based test framework To tie it all together, we'll build a simple annotation-based test framework. First we need a marker annotation type to indicate that a method is a test method, and should be run by the testing tool: import java.lang.annotation.*; /** * Indicates that the annotated method is a test method. * This annotation should be used only on parameterless static methods. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Test { }
  • 15. Annotation-based test framework Note that the annotation type declaration is itself annotated. Such annotations are called meta-annotations. The first (@Retention(RetentionPolicy.RUNTIME)) indicates that annotations with this type are to be retained by the VM so they can be read reflectively at run-time. The second (@Target(ElementType.METHOD)) indicates that this annotation type can be used to annotate only method declarations.
  • 16. Annotation-based test framework Here is a sample program, some of whose methods are annotated with the above interface: public class Foo { @Test public static void m1() { } public static void m2() { } @Test public static void m3() { } public static void m4() { } @Test public static void m5() { } }
  • 17. Annotation-based test framework import java.lang.reflect.*; public class RunTests { public static void main(String[] args) throws Exception { int passed = 0, failed = 0; for (Method m : Class.forName(args[0]).getMethods()) { if (m.isAnnotationPresent(Test.class)) { try { m.invoke(null); passed++; } catch (Throwable ex) { System.out.printf("Test %s failed: %s %n", m, ex.getCause()); failed++; } } } System.out.printf("Passed: %d, Failed %d%n", passed, failed); }