SlideShare una empresa de Scribd logo
1 de 29
Annotations in Java
Serhii Kartashov
April 2013
SoftServe
IFDC IT Academy
Agenda
What is Annotations?
Structure of Annotations
Annotations Types
Standard Java Annotations and Categories
Custom Annotations
Process Annotations
Agenda
What is Annotations?
Structure of Annotations
Annotations Types
Standard Java Annotations and Categories
Custom Annotations
Process Annotations
What is Annotations?
• Annotation is code about the code, that is
metadata about the program itself.
• Organized data about the code, included
within the code itself. It can be parsed by the
compiler, annotation processing tools and can
also be made available at run-time too.
What is Annotations?
public class MyClass implements Serializable {
private String f1;
private transient String f2;
}
/**
*
* @author Serhii K.
* @version 1.0
*
*/
public class MyClass implements Serializable {
Agenda
What is Annotations?
Structure of Annotations
Annotations Types
Standard Java Annotations and Categories
Custom Annotations
Process Annotations
Structure of Annotations
Every annotation belongs to a annotation type.
Annotation type is very similar to an interface with little difference:
• We attach ‘@’ just before interface keyword.
• Methods will not have parameters.
• Methods will not have throws clause.
• Method return types are restricted to primitives, String, Class, enums,
annotations, and arrays of the preceding types.
• We can set a default value to method.
@Documented, @Inherited, @Retention and @Target are the four available
meta annotations that are built-in with Java.
@interface <annotation_type_name> {
<method_declaration>;
}
Agenda
What is Annotations?
Structure of Annotations
Annotations Types
Standard Java Annotations and Categories
Custom Annotations
Process Annotations
Retention
This meta annotation denotes the level till which this annotation will be
carried. When an annotation type is annotated with meta annotation
Retention, RetentionPolicy has three possible values:
• Class
When the annotation value is given as ‘class’ then this annotation will be
compiled and included in the class file.
• Runtime
The value name itself says, when the retention value is ‘Runtime’ this
annotation will be available in JVM at runtime.
• Source
This annotation will be removed at compile time and will not be available
at compiled class.
@Retention(RetentionPolicy.RUNTIME)
public @interface MyClass {
String value();
}
Target
This meta annotation says that this annotation
type is applicable for only the element
(ElementType) listed.
Possible values for ElementType are,
CONSTRUCTOR, FIELD, LOCAL_VARIABLE,
METHOD, PACKAGE, PARAMETER, TYPE.
@Target(ElementType.FIELD)
public @interface MyClass {
}
Inherited
This meta annotation denotes that the
annotation type can be inherited from super
class. When a class is annotated with annotation
of type that is annotated with Inherited, then its
super class will be queried till a matching
annotation is found.
Documented
When a annotation type is annotated with
@Documented then wherever this annotation is
used those elements should be documented
using Javadoc tool
Agenda
What is Annotations?
Structure of Annotations
Annotations Types
Standard Java Annotations and Categories
Custom Annotations
Process Annotations
Annotations in Java - @Override
When we want to override a method, we can use this
annotation to say to the compiler we are overriding an
existing method.
If the compiler finds that there is no matching method found
in super class then generates a warning.
Though it is not mandatory, it is considered as a best practice.
@Override
public String toString( ) {
return super.toString( ) + " [modified by subclass]";
}
Annotations in Java - @Deprecated
When we want to inform the compiler that a method is deprecated we can use this.
So, when a method is annotated with @Deprecated and that method is found used in
some place, then the compiler generates a warning.
…
writingWithObjectOutputStream();
readingWithObjectOutputStream();
} catch (Exception e) {
e.printStackTrace();
}
}
@Deprecated
private static void readingWithObjectOutputStream() throws Exception {
FileInputStream in = new FileInputStream("objectStore.ser");
Annotations in Java -
@SuppressWarnings
This is like saying, “I know what I am doing, so please shut up!” We want the compiler not to raise any warnings and
then we use this annotation.
@SuppressWarnings({ "resource", "unused" })
//@SuppressWarnings(value={ "resource", "unused" })
private static void readingWithObjectOutputStream() throws Exception {
FileInputStream in = new FileInputStream("objectStore.ser");
//@SuppressWarnings("resource")
ObjectInputStream is = new ObjectInputStream(in);
//@SuppressWarnings("unused")
String note = (String)is.readObject();
MySerialClass serialIn1 = (MySerialClass)is.readObject();
serialIn1.toString();
}
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
String[] value();
}
unchecked
Categories of annotations
• Marker annotations have no variables. The annotation simply appears, identified
by name, with no additional data supplied.
For example, @MarkerAnnotation is a marker annotation.
It includes no data, just the annotation name.
• Single-value annotations are similar to markers, but provide a single piece of data.
Because only a single bit of data is supplied, you can use a shortcut syntax
(assuming the annotation type is defined to accept this syntax):
@SingleValueAnnotation("my data")
• Full annotations have multiple data members. As a result, you must use a fuller
syntax (and the annotation doesn't look quite so much like a normal Java method
anymore):
@FullAnnotation(var1="data value 1",
var2="data value 2",
var3="data value 3")
Custom annotations
1. The @interface declaration
Defining a new annotation type is a lot like creating an interface,
except that you precede the interface keyword with the @ sign.
package org.kartashov;
/**
* Annotation type to indicate a task still needs to be
* completed.
*/
public @interface TODO {
}
Agenda
What is Annotations?
Structure of Annotations
Annotations Types
Standard Java Annotations and Categories
Custom Annotations
Process Annotations
Custom annotations
2. Adding a member
package org.kartashov;
/**
* Annotation type to indicate a task still needs to be
* completed.
*/
public @interface TODO {
String value();
//String[] value();
}
Custom annotations
3. Setting default values
package org.kartashov;
public @interface GroupTODO {
public enum Severity { CRITICAL, IMPORTANT, TRIVIAL, DOCUMENTATION };
Severity severity() default Severity.IMPORTANT; String item();
String assignedTo();
String dateAssigned();
}
@GroupTODO(
item="Figure out the amount of interest per month",
assignedTo="Brett McLaughlin",
dateAssigned="08/04/2004" )
public void calculateInterest(float amount, float rate) {
…
}
Agenda
What is Annotations?
Structure of Annotations
Annotations Types
Standard Java Annotations and Categories
Custom Annotations
Process Annotations
Process Annotations
At the first lets create own custom annotation:
package org.kartashov.annotations.reflection.developer;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Developer {
String value();
}
Process Annotations
Create simple java class with and use our annotations:
package org.kartashov.annotations.reflection.developer;
public class BuildHouse {
@Developer ("Alice")
public void aliceMethod() {
System.out.println("This method is written by Alice");
}
@Developer ("Popeye")
public void buildHouse() {
System.out.println("This method is written by Popeye");
}
}
Process Annotations
Lets build GNUMain method:
1.
for (Method method : Class.forName(
"org.kartashov.annotations.reflection.developer.BuildHouse").getMethods()) {
2.
if (method.isAnnotationPresent(Developer.class)) {
3.
for (Annotation anno : method.getDeclaredAnnotations()) {
4.
Developer a = method.getAnnotation(Developer.class);
5.
if ("Popeye".equals(a.value())) {
System.out.println("Popeye the sailor man! " + method);
}
}
Hibernate Example
@Column(name = "STOCK_CODE", unique = true,
nullable = false, length = 10)
public String getStockCode() {
return this.stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
Home Work
Create your own test framework like JUnit.
You have to manage follow features:
1. all test methods should be marked with help
@Test annotation.
2. this annotations should support “description”
and “count” (how many times run this test)
parameters
3. implement simple static assert methods (core
your test framework)
4. print result of tests to simple java console.
Questions
and
Answers
Useful links
• Links
– http://www.ibm.com/developerworks/library/j-annotate1/
– http://www.ibm.com/developerworks/library/j-
annotate2/index.html

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Interface
InterfaceInterface
Interface
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 

Destacado

Python pune talk decorators
Python pune talk   decoratorsPython pune talk   decorators
Python pune talk decoratorsSid Saha
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in PythonBen James
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Androidemanuelez
 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughMahfuz Islam Bhuiyan
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 

Destacado (18)

Java Annotation
Java AnnotationJava Annotation
Java Annotation
 
Python pune talk decorators
Python pune talk   decoratorsPython pune talk   decorators
Python pune talk decorators
 
Java annotation
Java annotationJava annotation
Java annotation
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
JSP
JSPJSP
JSP
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner Walkthrough
 
Annotations in Java
Annotations in JavaAnnotations in Java
Annotations in Java
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 

Similar a Java Annotations

Eclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDTEclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDTdeepakazad
 
Java annotations
Java annotationsJava annotations
Java annotationsSujit Kumar
 
Introduction
IntroductionIntroduction
Introductionrichsoden
 
Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_springGuo Albert
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfacesDevaKumari Vijay
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfacesKalai Selvi
 
Krazykoder struts2 annotations
Krazykoder struts2 annotationsKrazykoder struts2 annotations
Krazykoder struts2 annotationsKrazy Koder
 
Write code that writes code! A beginner's guide to Annotation Processing - Ja...
Write code that writes code! A beginner's guide to Annotation Processing - Ja...Write code that writes code! A beginner's guide to Annotation Processing - Ja...
Write code that writes code! A beginner's guide to Annotation Processing - Ja...DroidConTLV
 
Write code that writes code!
Write code that writes code!Write code that writes code!
Write code that writes code!Jason Feinstein
 
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)David McCarter
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in JavaGurpreet singh
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 

Similar a Java Annotations (20)

Annotations
AnnotationsAnnotations
Annotations
 
Eclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDTEclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDT
 
Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
 
Java annotations
Java annotationsJava annotations
Java annotations
 
Introduction
IntroductionIntroduction
Introduction
 
Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_spring
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
 
Krazykoder struts2 annotations
Krazykoder struts2 annotationsKrazykoder struts2 annotations
Krazykoder struts2 annotations
 
Write code that writes code! A beginner's guide to Annotation Processing - Ja...
Write code that writes code! A beginner's guide to Annotation Processing - Ja...Write code that writes code! A beginner's guide to Annotation Processing - Ja...
Write code that writes code! A beginner's guide to Annotation Processing - Ja...
 
Write code that writes code!
Write code that writes code!Write code that writes code!
Write code that writes code!
 
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)
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Annotations
AnnotationsAnnotations
Annotations
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Annotations Processor Tools (APT)
Annotations Processor Tools (APT)Annotations Processor Tools (APT)
Annotations Processor Tools (APT)
 
iOS Application Development
iOS Application DevelopmentiOS Application Development
iOS Application Development
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
J2ee standards > CDI
J2ee standards > CDIJ2ee standards > CDI
J2ee standards > CDI
 

Último

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 

Último (20)

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 

Java Annotations

  • 1. Annotations in Java Serhii Kartashov April 2013 SoftServe IFDC IT Academy
  • 2. Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 3. Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 4. What is Annotations? • Annotation is code about the code, that is metadata about the program itself. • Organized data about the code, included within the code itself. It can be parsed by the compiler, annotation processing tools and can also be made available at run-time too.
  • 5. What is Annotations? public class MyClass implements Serializable { private String f1; private transient String f2; } /** * * @author Serhii K. * @version 1.0 * */ public class MyClass implements Serializable {
  • 6. Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 7. Structure of Annotations Every annotation belongs to a annotation type. Annotation type is very similar to an interface with little difference: • We attach ‘@’ just before interface keyword. • Methods will not have parameters. • Methods will not have throws clause. • Method return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. • We can set a default value to method. @Documented, @Inherited, @Retention and @Target are the four available meta annotations that are built-in with Java. @interface <annotation_type_name> { <method_declaration>; }
  • 8. Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 9. Retention This meta annotation denotes the level till which this annotation will be carried. When an annotation type is annotated with meta annotation Retention, RetentionPolicy has three possible values: • Class When the annotation value is given as ‘class’ then this annotation will be compiled and included in the class file. • Runtime The value name itself says, when the retention value is ‘Runtime’ this annotation will be available in JVM at runtime. • Source This annotation will be removed at compile time and will not be available at compiled class. @Retention(RetentionPolicy.RUNTIME) public @interface MyClass { String value(); }
  • 10. Target This meta annotation says that this annotation type is applicable for only the element (ElementType) listed. Possible values for ElementType are, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE. @Target(ElementType.FIELD) public @interface MyClass { }
  • 11. Inherited This meta annotation denotes that the annotation type can be inherited from super class. When a class is annotated with annotation of type that is annotated with Inherited, then its super class will be queried till a matching annotation is found.
  • 12. Documented When a annotation type is annotated with @Documented then wherever this annotation is used those elements should be documented using Javadoc tool
  • 13. Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 14. Annotations in Java - @Override When we want to override a method, we can use this annotation to say to the compiler we are overriding an existing method. If the compiler finds that there is no matching method found in super class then generates a warning. Though it is not mandatory, it is considered as a best practice. @Override public String toString( ) { return super.toString( ) + " [modified by subclass]"; }
  • 15. Annotations in Java - @Deprecated When we want to inform the compiler that a method is deprecated we can use this. So, when a method is annotated with @Deprecated and that method is found used in some place, then the compiler generates a warning. … writingWithObjectOutputStream(); readingWithObjectOutputStream(); } catch (Exception e) { e.printStackTrace(); } } @Deprecated private static void readingWithObjectOutputStream() throws Exception { FileInputStream in = new FileInputStream("objectStore.ser");
  • 16. Annotations in Java - @SuppressWarnings This is like saying, “I know what I am doing, so please shut up!” We want the compiler not to raise any warnings and then we use this annotation. @SuppressWarnings({ "resource", "unused" }) //@SuppressWarnings(value={ "resource", "unused" }) private static void readingWithObjectOutputStream() throws Exception { FileInputStream in = new FileInputStream("objectStore.ser"); //@SuppressWarnings("resource") ObjectInputStream is = new ObjectInputStream(in); //@SuppressWarnings("unused") String note = (String)is.readObject(); MySerialClass serialIn1 = (MySerialClass)is.readObject(); serialIn1.toString(); } @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings { String[] value(); } unchecked
  • 17. Categories of annotations • Marker annotations have no variables. The annotation simply appears, identified by name, with no additional data supplied. For example, @MarkerAnnotation is a marker annotation. It includes no data, just the annotation name. • Single-value annotations are similar to markers, but provide a single piece of data. Because only a single bit of data is supplied, you can use a shortcut syntax (assuming the annotation type is defined to accept this syntax): @SingleValueAnnotation("my data") • Full annotations have multiple data members. As a result, you must use a fuller syntax (and the annotation doesn't look quite so much like a normal Java method anymore): @FullAnnotation(var1="data value 1", var2="data value 2", var3="data value 3")
  • 18. Custom annotations 1. The @interface declaration Defining a new annotation type is a lot like creating an interface, except that you precede the interface keyword with the @ sign. package org.kartashov; /** * Annotation type to indicate a task still needs to be * completed. */ public @interface TODO { }
  • 19. Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 20. Custom annotations 2. Adding a member package org.kartashov; /** * Annotation type to indicate a task still needs to be * completed. */ public @interface TODO { String value(); //String[] value(); }
  • 21. Custom annotations 3. Setting default values package org.kartashov; public @interface GroupTODO { public enum Severity { CRITICAL, IMPORTANT, TRIVIAL, DOCUMENTATION }; Severity severity() default Severity.IMPORTANT; String item(); String assignedTo(); String dateAssigned(); } @GroupTODO( item="Figure out the amount of interest per month", assignedTo="Brett McLaughlin", dateAssigned="08/04/2004" ) public void calculateInterest(float amount, float rate) { … }
  • 22. Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 23. Process Annotations At the first lets create own custom annotation: package org.kartashov.annotations.reflection.developer; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Developer { String value(); }
  • 24. Process Annotations Create simple java class with and use our annotations: package org.kartashov.annotations.reflection.developer; public class BuildHouse { @Developer ("Alice") public void aliceMethod() { System.out.println("This method is written by Alice"); } @Developer ("Popeye") public void buildHouse() { System.out.println("This method is written by Popeye"); } }
  • 25. Process Annotations Lets build GNUMain method: 1. for (Method method : Class.forName( "org.kartashov.annotations.reflection.developer.BuildHouse").getMethods()) { 2. if (method.isAnnotationPresent(Developer.class)) { 3. for (Annotation anno : method.getDeclaredAnnotations()) { 4. Developer a = method.getAnnotation(Developer.class); 5. if ("Popeye".equals(a.value())) { System.out.println("Popeye the sailor man! " + method); } }
  • 26. Hibernate Example @Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10) public String getStockCode() { return this.stockCode; } public void setStockCode(String stockCode) { this.stockCode = stockCode; }
  • 27. Home Work Create your own test framework like JUnit. You have to manage follow features: 1. all test methods should be marked with help @Test annotation. 2. this annotations should support “description” and “count” (how many times run this test) parameters 3. implement simple static assert methods (core your test framework) 4. print result of tests to simple java console.
  • 29. Useful links • Links – http://www.ibm.com/developerworks/library/j-annotate1/ – http://www.ibm.com/developerworks/library/j- annotate2/index.html