SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Java features
Java featuresJava features
Java features
Prashant Gajendra
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
Ganesh Samarthyam
 
Bt0074 oops with java
Bt0074 oops with javaBt0074 oops with java
Bt0074 oops with java
Techglyphs
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
arnold 7490
 
The Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.NetThe Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.Net
Anand Kumar Rajana
 
Java Basics
Java BasicsJava Basics
Java Basics
shivamgarg_nitj
 
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...
Jorge Hidalgo
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Java annotations
Java annotationsJava annotations
Java annotations
Sujit Kumar
 
Java basic
Java basicJava basic
Java basic
Arati Gadgil
 
Core java
Core javaCore java
Core java
Shivaraj R
 
Java se 8 fundamentals
Java se 8 fundamentalsJava se 8 fundamentals
Java se 8 fundamentals
megharajk
 
PHP 5
PHP 5PHP 5
PHP 5
Rafael Corral
 
Getting Program Input
Getting Program Input Getting Program Input
Getting Program Input
Dr. Rosemarie Sibbaluca-Guirre
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
Dr. Rosemarie Sibbaluca-Guirre
 
Java programming(unit 1)
Java programming(unit 1)Java programming(unit 1)
Java programming(unit 1)
Dr. SURBHI SAROHA
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for Productivity
David Noble
 
java programming - applets
java programming - appletsjava programming - applets
java programming - applets
HarshithaAllu
 
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
Raffi Khatchadourian
 
Interface java
Interface java Interface java
Interface java
atiafyrose
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
Ganesh Samarthyam
 
Bt0074 oops with java
Bt0074 oops with javaBt0074 oops with java
Bt0074 oops with java
Techglyphs
 
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...
Jorge Hidalgo
 
Java annotations
Java annotationsJava annotations
Java annotations
Sujit Kumar
 
Java se 8 fundamentals
Java se 8 fundamentalsJava se 8 fundamentals
Java se 8 fundamentals
megharajk
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for Productivity
David Noble
 
java programming - applets
java programming - appletsjava programming - applets
java programming - applets
HarshithaAllu
 
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
Raffi Khatchadourian
 
Interface java
Interface java Interface java
Interface java
atiafyrose
 

Viewers also liked (20)

Interactive web prototyping
Interactive web prototypingInteractive web prototyping
Interactive web prototyping
Ecommerce Solution Provider SysIQ
 
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
Ecommerce Solution Provider SysIQ
 
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Ecommerce Solution Provider SysIQ
 
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
Ecommerce Solution Provider SysIQ
 
Getting to know magento
Getting to know magentoGetting to know magento
Getting to know magento
Ecommerce Solution Provider SysIQ
 
Quick Intro to Clean Coding
Quick Intro to Clean CodingQuick Intro to Clean Coding
Quick Intro to Clean Coding
Ecommerce Solution Provider SysIQ
 
Эффективный JavaScript - IQLab Frontend Fusion 2012
Эффективный  JavaScript - IQLab Frontend Fusion 2012Эффективный  JavaScript - IQLab Frontend Fusion 2012
Эффективный JavaScript - IQLab Frontend Fusion 2012
Ecommerce Solution Provider SysIQ
 
Developing for e commerce is important
Developing for e commerce is importantDeveloping for e commerce is important
Developing for e commerce is important
Ecommerce Solution Provider SysIQ
 
Java serialization
Java serializationJava serialization
Java serialization
Ecommerce Solution Provider SysIQ
 
IGears: Template Architecture and Principles
IGears: Template Architecture and PrinciplesIGears: Template Architecture and Principles
IGears: Template Architecture and Principles
Ecommerce Solution Provider SysIQ
 
QA evolution to the present day
QA evolution to the present dayQA evolution to the present day
QA evolution to the present day
Ecommerce Solution Provider SysIQ
 
User focused design
User focused designUser focused design
User focused design
Ecommerce Solution Provider SysIQ
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Ecommerce Solution Provider SysIQ
 
Эффективный JavaScript - IQLab Frontend Fusion 2012
Эффективный  JavaScript - IQLab Frontend Fusion 2012Эффективный  JavaScript - IQLab Frontend Fusion 2012
Эффективный JavaScript - IQLab Frontend Fusion 2012
Ecommerce Solution Provider SysIQ
 
Ad

Similar to Understanding Annotations in Java (20)

Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
emanuelez
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
vanithaRamasamy
 
Junit4.0
Junit4.0Junit4.0
Junit4.0
gouthamrv
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
Rich Helton
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
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
Partnered Health
 
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptxModule 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
SMIJava
 
01slide
01slide01slide
01slide
Usha Sri
 
01slide
01slide01slide
01slide
cdclabs_123
 
Packages and Java Library: Introduction, Defining Package, Importing Packages...
Packages and Java Library: Introduction, Defining Package, Importing Packages...Packages and Java Library: Introduction, Defining Package, Importing Packages...
Packages and Java Library: Introduction, Defining Package, Importing Packages...
kamalabhushanamnokki
 
Packages and Java Library: Introduction, Defining Package, Importing Packages...
Packages and Java Library: Introduction, Defining Package, Importing Packages...Packages and Java Library: Introduction, Defining Package, Importing Packages...
Packages and Java Library: Introduction, Defining Package, Importing Packages...
kamalabhushanamnokki
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
i i
 
Annotations in Java Why are they important.pptx
Annotations in Java Why are they important.pptxAnnotations in Java Why are they important.pptx
Annotations in Java Why are they important.pptx
agonmustafa4
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
SudhanshiBakre1
 
Java notes
Java notesJava notes
Java notes
Upasana Talukdar
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
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
Shivam Singhal
 
Jacarashed-1746968053-300050282-Java.ppt
Jacarashed-1746968053-300050282-Java.pptJacarashed-1746968053-300050282-Java.ppt
Jacarashed-1746968053-300050282-Java.ppt
DilipDas70
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
emanuelez
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
Rich Helton
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
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
Partnered Health
 
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptxModule 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
SMIJava
 
Packages and Java Library: Introduction, Defining Package, Importing Packages...
Packages and Java Library: Introduction, Defining Package, Importing Packages...Packages and Java Library: Introduction, Defining Package, Importing Packages...
Packages and Java Library: Introduction, Defining Package, Importing Packages...
kamalabhushanamnokki
 
Packages and Java Library: Introduction, Defining Package, Importing Packages...
Packages and Java Library: Introduction, Defining Package, Importing Packages...Packages and Java Library: Introduction, Defining Package, Importing Packages...
Packages and Java Library: Introduction, Defining Package, Importing Packages...
kamalabhushanamnokki
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
i i
 
Annotations in Java Why are they important.pptx
Annotations in Java Why are they important.pptxAnnotations in Java Why are they important.pptx
Annotations in Java Why are they important.pptx
agonmustafa4
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
SudhanshiBakre1
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
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
Shivam Singhal
 
Jacarashed-1746968053-300050282-Java.ppt
Jacarashed-1746968053-300050282-Java.pptJacarashed-1746968053-300050282-Java.ppt
Jacarashed-1746968053-300050282-Java.ppt
DilipDas70
 
Ad

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
Ecommerce Solution Provider SysIQ
 
Magento code audit
Magento code auditMagento code audit
Magento code audit
Ecommerce Solution Provider SysIQ
 
Scalability and performance for e commerce
Scalability and performance for e commerceScalability and performance for e commerce
Scalability and performance for e commerce
Ecommerce Solution Provider SysIQ
 
Going global
Going globalGoing global
Going global
Ecommerce Solution Provider SysIQ
 
Going Global
Going GlobalGoing Global
Going Global
Ecommerce Solution Provider SysIQ
 
QA evolution, in pictures
QA evolution, in picturesQA evolution, in pictures
QA evolution, in pictures
Ecommerce Solution Provider SysIQ
 
Management and Communications (IPAA)
Management and Communications (IPAA)Management and Communications (IPAA)
Management and Communications (IPAA)
Ecommerce Solution Provider SysIQ
 
Правила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработкеПравила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработке
Ecommerce Solution Provider SysIQ
 
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
Ecommerce Solution Provider SysIQ
 

Recently uploaded (20)

Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 

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); }
  翻译: