SlideShare a Scribd company logo
1 of 40
Download to read offline
By
Java Annotations
• Before the advent of Annotations, you don’t need to define your source code metadata
outside in some properties file.
• Now, they can directly define this meta-data information in the source code itself.
• If used this feature wisely (as it is used in latest java frameworks like Spring and Strutc),
benefits are countless.
Java Annotations - History
• The Java platform has various ad-hoc annotation mechanisms—for example, the transient
modifier, or the @deprecated javadoc tag.
• JSR-175 introduced the general-purpose annotation (also known as metadata) facility to
the Java Community Process in 2002; it gained approval in September 2004.
• Annotations became available in the language itself beginning with version 1.5 of the JDK.
• The apt tool provided a provisional interface for compile-time annotation processing in
JDK version 1.5; JSR-269 formalized this, and it became integrated into the javac compiler
in version 1.6.
Java Annotations in 5 Steps
1. Annotations are metadata which can be applied on either annotations OR other java
element in java source code.
2. 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.
3. Annotations can be read from source files, class files, or reflectively at run time.
4. There are 10 in-built annotations as of today. 5 of them are meant to be applied on
custom annotations and other 5 are meant to be applied on java source code
elements.
5. Because annotation types are compiled and stored in byte code files just like classes,
the annotations returned by these methods can be queried just like any regular Java
object.
Why annotations?
• Introduced in Java in the J2SE update 5 already and the main reason was the need to
provide a mechanism that allows programmers to write metadata about their code
directly in the code itself.
• Before annotations, the way programmers were describing their code was not
standardized and each developer did it in his own original way: using transient keywords,
via comments, with interfaces, etc. This was not a good approach and a decision was
taken: a new form of metadata is going to be available in Java, annotations were
introduced.
Why annotations? (Contd…)
• At that moment, XML was used as standard code configuration mechanism for different
type of applications. This was not the best way to do it because of the decoupling
between code and XML (XML is not code!) and the future maintenance of this decoupled
applications.
• There were other reasons like for example the usage of the reserved word
“@deprecated” (with small d) in the Javadocs since Java update 4, I am very sure that this
was one of the reasons for the current annotations syntax using the “@”.
When Not to Use Annotations
• Do not over use annotation as it will pollute the code.
• It is better not to try to change the behavior of objects using annotations.
• There is sufficient constructs available in oops and annotation is not a better mechanism
to deal with it.
• Do not try to over generalize as it may complicate the underlying code. Code is the real
program and annotation is meta.
• Avoid using annotation to specify environment / application / database related
information.
Use cases
• Annotations can be used for many different purposes, the most common ones are:
1. Information for the compiler: Annotations can be used by the compiler to produce
warnings or even errors based on different rules. One example of this kind of usage is
the Java 8 @Functional Interface annotation. This one makes the compiler to validate
the annotated class and check if it is a correct functional interface or not.
2. Documentation: Annotations can be used by software applications to measure the
quality of the code like Find Bugs or PMD do or generate reports automatically like
Jenkins, Jira or Team city.
3. Code generation: annotations can be used to generate code or XML files automatically
using metadata information present in the code. A good example of this is the JAXB
library.
4. Runtime processing: Annotations that are examined in runtime can be used for
different objectives like unit testing (Junit), dependency injection (Spring), validation,
logging (Log4J) ,data access (Hibernate) etc.
Annotation Structure
• There are two main components in annotations.
1. First is annotation type
2. Second is the annotation itself which we use in the code to add meaning.
• Every annotation belongs to a annotation type.
Annotation Type
• Annotation type is very similar to an interface with little difference.
1. We attach ‘@’ just before interface keyword.
2. Methods will not have parameters.
3. Methods will not have throws clause.
4. Method return types are restricted to primitives, String, Class, enums,
annotations, and arrays of the preceding types.
5. We can assign a default value to method.
@interface
{
method declaration;
}
Meta Annotations
• Annotations itself is meta information then what is meta annotations? It is
information about annotation.
• When we annotate a annotation type then it is called meta annotation.
• For example, we say that this annotation can be used only for methods.
@Target(ElementType.METHOD)
public @interface MethodInfo
{
}
Annotation Types
• Documented
When a annotation type is annotated with @Documented then wherever this
annotation is used those elements should be documented using Javadoc tool.
import java.lang.annotation.Documented;
@Documented
public @interface MyAnnotation {
}
@MyAnnotation
public class MySuperClass
{ ... }
When generating JavaDoc for the MySuperClass class,
the @MyAnnotation is now included in the JavaDoc.
Annotation Types (Contd…)
• @Inherited
The @Inherited annotation signals that a custom Java annotation used in a class should be
inherited by subclasses inheriting from that class. Here is an @Inherited Java annotation
example:
java.lang.annotation.Inherited
@Inherited
public @interface MyAnnotation {
}
@MyAnnotation
public class MySuperClass { ... }
public class MySubClass extends MySuperClass { ... }
The class MySubClass inherits the annotation @MyAnnotation because
MySubClass inherits from MySuperClass, and MySuperClass has a @MyAnnotation
annotation.
Annotation Types (Contd…)
• @Target
You can specify which Java elements your custom annotation can be used to annotate. You
do so by annotating your annotation definition with the @Target annotation.
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
public @interface MyAnnotation {
String value();
}
This example shows a Java annotation that can only be used to annotate methods.
Annotation Types (Contd…)
• @Target (Contd…)
• The ElementType class contains the following possible targets:
• ElementType.ANNOTATION_TYPE
• ElementType.CONSTRUCTOR
• ElementType.FIELD
• ElementType.LOCAL_VARIABLE
• ElementType.METHOD
• ElementType.PACKAGE
• ElementType.PARAMETER
• ElementType.TYPE
The ANNOTATION_TYPE target means Java annotation
definitions. Thus, the annotation can only be used to annotate
other annotations. Like the @Target and @Retention
annotations.
The TYPE target means any type. A type is either a class,
interface, enum or annotation.
Annotation Types (Contd…)
• @Target (Contd…) : A Typical Implementation of @Target
@Target({ElementType.TYPE,ElementType.METHOD,
ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE,
ElementType.PACKAGE,ElementType.FIELD,ElementType.LOCAL_VARIABLE})
Annotation Types (Contd…)
• @Retention
You can specify for your custom annotation if it should be available at runtime, for
inspection via reflection. You do so by annotating your annotation definition with the
@Retention annotation. Here is how that is done:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value() default "";
}
Runtime
The value name itself says, when the retention value is
‘Runtime’ this annotation will be available in JVM at
runtime. We can write custom code using reflection
package and parse the annotation.
Annotation Types (Contd…)
• @Retention (Contd…)
• The RetentionPolicy class contains two more values you can use:
1. RetentionPolicy.CLASS means that the annotation is stored in the .class file, but not
available at runtime. This is the default retention policy.
2. RetentionPolicy.SOURCE This annotation will be removed at compile time and will not
be available at compiled class.
Java Annotation Purposes
• Java annotations are typically used for the following purposes:
1. Compiler instructions
2. Build-time instructions
3. Runtime instructions
Built-in Java Annotations
• Java comes with three built-in annotations which are used to give the Java compiler
instructions.
1. @Deprecated
2. @Override
3. @SuppressWarnings
@Deprecated
• Used to mark a class, method or field as deprecated, meaning it should no longer be
used.
• If your code uses deprecated classes, methods or fields, the compiler will give you a
warning.
• Example:
@Deprecated
public class MyComponent {
}
You can also use the @Deprecated annotation above method and field declarations, to
mark the method or field as deprecated.
@Override
• Used above methods that override methods in a superclass.
• If the method does not match a method in the superclass, the compiler will give you an
error.
• The @Override annotation is not necessary in order to override a method in a superclass.
• It is a good idea to use it still, though. In case someone changed the name of the
overridden method in the superclass, your subclass method would no longer override it.
• With the @Override annotation the compiler would tell you that the method in the
subclass is not overriding any method in the superclass.
@Override (Contd…)
Example:
public class Super_Class {
public void doTheThing() {
System.out.println("Do the thing");
}
}
public class Sub_Class extends Super_Class{
@Override
public void doTheThing() {
System.out.println("Do it differently");
}
}
“In case the method doTheThing() in
Super_Class changes signature so that the
same method in the subclass no longer
overrides it, the compiler will generate an
error.”
@Override (Contd…)
package Annot;
class ParentClass
{
public void displayMethod(String msg){
System.out.println(msg);
}
}
class SubClass extends ParentClass
{
@Override
public void displayMethod(String msg){
System.out.println("Message is: "+ msg);
}
public static void main(String args[]){
SubClass obj = new SubClass();
obj.displayMethod("Hey!!");
}
}
Output:
Message is: Hey!!
Why we use @Override annotation
1. If programmer makes any mistake such as wrong method name, wrong parameter types
while overriding, you would get a compile time error. As by using this annotation you
instruct compiler that you are overriding this method. If you don’t use the annotation
then the sub class method would behave as a new method (not the overriding method)
in sub class.
2. It improves the readability of the code. So if you change the signature of overridden
method then all the sub classes that overrides the particular method would throw a
compilation error, which would eventually help you to change the signature in the sub
classes. If you have lots of classes in your application then this annotation would really
help you to identify the classes that require changes when you change the signature of
a method.
@SuppressWarnings
• Makes the compiler suppress warnings for a given method.
• For instance, if a method calls a deprecated method, or makes an insecure type cast, the
compiler may generate a warning.
• You can suppress these warnings by annotating the method containing the code with the
@SuppressWarnings annotation.
• Example:
@SuppressWarnings
public void methodWithWarning()
{
}
@SuppressWarnings (Contd…)
package Annot;
public class Supress {
@Deprecated
public void showDeprecatedMessage(){
System.out.println("This method is marked as deprecated");
}
@SuppressWarnings("deprecation")
public static void main(String a[]){
Supress spw = new Supress();
spw.showDeprecatedMessage();
}
}
Output:
This method is marked as deprecated
Categories of annotations
• Marker annotations have no variables. The annotation simply appears, identified by
name, with no additional data supplied. The @Override and @Deprecated are marker
annotations.
For example, @MarkerAnnotation is a marker annotation. It includes no data, just the
annotation name.
Categories of annotations(Contd…)
• Single-value annotations are similar to markers, but provide a single piece of data.
Because only a single bit of data is supplied.
• An annotation that has one method, is called single-value annotation.
• Example:
• The code to apply the single value annotation
@interface MyAnnotation{
int value() default 0;
}
@MyAnnotation(value=10)
Categories of annotations(Contd…)
• Full annotations have multiple data members. As a result, you must use a fuller syntax
@FullAnnotation(var1="data value 1",
var2="data value 2",
var3="data value 3")
Custom Annotations
To create a custom annotation, you must use the keyword “@interface“. Other important
things to remember while creating custom annotations are listed below:
• Each method declaration defines an element of the annotation type.
• Method declarations must not have any parameters or a throws clause.
• Return types are restricted to primitives, String, Class, enums, annotations, and arrays of
the preceding types.
• Methods can have default values.
Custom Annotations (Contd…)
package Custom.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface customFile1
{
String author() default "unknown";
String version() default "0.0";
}
package Custom.Annotation;
@customFile1
public class CustomClass1
{
@customFile1(author = "Anjum", version = "1.0")
public String getString()
{
return null;
}
}
Custom Annotations (Contd…)
package Custom.Annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
public class MainClass
{
public static void main(String[] args) throws NoSuchMethodException, SecurityException
{
new CustomClass1();
Class<CustomClass1> cc1 = CustomClass1.class;
readAnnotationOn(cc1);
Method method = cc1.getMethod("getString", new Class[]{});
readAnnotationOn(method);
}
Custom Annotations (Contd…)
static void readAnnotationOn(AnnotatedElement element){
try {
System.out.println("n Finding annotations on " + element.getClass().getName());
Annotation[] annotations = element.getAnnotations();
for (Annotation annotation : annotations){
if (annotation instanceof customFile1)
{
customFile1 cf1 = (customFile1) annotation;
System.out.println("Author :" + cf1.author());
System.out.println("Version :" + cf1.version());
}
}
} catch (Exception e) { e.printStackTrace();}}}
Custom Annotations (Contd…)
Output:
Finding annotations on java.lang.Class
Author :unknown
Version :0.0
Finding annotations on
java.lang.reflect.Method
Author :Anjum
Version :1.0
Fetching Annotation Info
• Reflection API can be used to explore the Annotation details at runtime
programmatically .
• Syntax: isAnnotationPresent()
Fetching Annotation Info (Contd…)
• Example:
package Annot;
public class IsAnnotPres {
public static void main(String[] unused) {
try {
String n = "java.lang.Deprecated";
Class c = Class.forName(n);
Class d = Class.forName("java.util.Date");
System.out.println("Status of Annotation: " +d.isAnnotationPresent(c));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Output:
Status of Annotation: false
Annotations applied to Java code:
• @Override - Checks that the method is an override. Causes a compile error if the method
is not found in one of the parent classes or implemented interfaces.
• @Deprecated - Marks the method as obsolete. Causes a compile warning if the method is
used.
• @SuppressWarnings - Instructs the compiler to suppress the compile time warnings
specified in the annotation parameters.
• @SafeVarargs - Suppress warnings for all callers of a method or constructor with a
generics varargs parameter, since Java 7.
• @FunctionalInterface - Specifies that the type declaration is intended to be a functional
interface, since Java 8.
Annotations applied to other annotations
(also known as "Meta Annotations"):
• @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.
• @Target - Marks another annotation to restrict what kind of Java elements the annotation
may be applied to.
• @Inherited - Marks another annotation to be inherited to subclasses of annotated class (by
default annotations are not inherited to subclasses).
• @Repeatable - Specifies that the annotation can be applied more than once to the same
declaration, since Java 8.
Java annotations

More Related Content

What's hot

javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
L21 io streams
L21 io streamsL21 io streams
L21 io streamsteach4uin
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptxParvizMirzayev2
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesHitesh-Java
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 

What's hot (20)

javascript objects
javascript objectsjavascript objects
javascript objects
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Data types in java
Data types in javaData types in java
Data types in java
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Strings in c#
Strings in c#Strings in c#
Strings in c#
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptx
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
Java input
Java inputJava input
Java input
 

Viewers also liked

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
 
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
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8José Paumard
 
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
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nousJosé Paumard
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 

Viewers also liked (16)

Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner Walkthrough
 
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
 
Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
 
Annotations
AnnotationsAnnotations
Annotations
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
 
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
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nous
 
Annotations in Java
Annotations in JavaAnnotations in Java
Annotations in Java
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 

Similar to Java annotations

Java annotations
Java annotationsJava annotations
Java annotationsSujit Kumar
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and AnnotationsAnuj Singh Rajput
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdfSudhanshiBakre1
 
Enumerations in java.pptx
Enumerations in java.pptxEnumerations in java.pptx
Enumerations in java.pptxSrizan Pokrel
 
Perfomatix - iOS swift coding standards
Perfomatix - iOS swift coding standardsPerfomatix - iOS swift coding standards
Perfomatix - iOS swift coding standardsPerfomatix Solutions
 
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 for Mainframers
Java for MainframersJava for Mainframers
Java for MainframersRich Helton
 
Java Coding Conventions
Java Coding ConventionsJava Coding Conventions
Java Coding ConventionsRodel Barcenas
 
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
A-Brief-Introduction-To-JAVA8_By_Srimanta_SahuA-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
A-Brief-Introduction-To-JAVA8_By_Srimanta_SahuSrimanta Sahu
 
1. Coding Conventions [Part 2]
1. Coding Conventions [Part 2]1. Coding Conventions [Part 2]
1. Coding Conventions [Part 2]Hardik Patel
 
Best practices in enterprise applications
Best practices in enterprise applicationsBest practices in enterprise applications
Best practices in enterprise applicationsChandra Sekhar Saripaka
 

Similar to Java annotations (20)

Annotations
AnnotationsAnnotations
Annotations
 
Java annotations
Java annotationsJava annotations
Java annotations
 
Java Custom Annotations- Part1
Java Custom Annotations- Part1Java Custom Annotations- Part1
Java Custom Annotations- Part1
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and Annotations
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
 
Enumerations in java.pptx
Enumerations in java.pptxEnumerations in java.pptx
Enumerations in java.pptx
 
Class method
Class methodClass method
Class method
 
Perfomatix - iOS swift coding standards
Perfomatix - iOS swift coding standardsPerfomatix - iOS swift coding standards
Perfomatix - iOS swift coding standards
 
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...
 
Coding
CodingCoding
Coding
 
java token
java tokenjava token
java token
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
Learn java theory presentation
Learn java theory presentationLearn java theory presentation
Learn java theory presentation
 
Java Coding Conventions
Java Coding ConventionsJava Coding Conventions
Java Coding Conventions
 
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
A-Brief-Introduction-To-JAVA8_By_Srimanta_SahuA-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
 
1. Coding Conventions [Part 2]
1. Coding Conventions [Part 2]1. Coding Conventions [Part 2]
1. Coding Conventions [Part 2]
 
NamingConvention
NamingConventionNamingConvention
NamingConvention
 
JAVA PROGRAMMING
JAVA PROGRAMMINGJAVA PROGRAMMING
JAVA PROGRAMMING
 
Best practices in enterprise applications
Best practices in enterprise applicationsBest practices in enterprise applications
Best practices in enterprise applications
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 

More from FAROOK Samath

More from FAROOK Samath (7)

Junit
JunitJunit
Junit
 
Group discussion
Group discussionGroup discussion
Group discussion
 
Coding standard
Coding standardCoding standard
Coding standard
 
Leadership skills
Leadership skillsLeadership skills
Leadership skills
 
Conference technique
Conference techniqueConference technique
Conference technique
 
Time management
Time managementTime management
Time management
 
Email Etiquette
Email EtiquetteEmail Etiquette
Email Etiquette
 

Recently uploaded

Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
WomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyoneWomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyoneUiPathCommunity
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 

Recently uploaded (20)

Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
WomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyoneWomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyone
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 

Java annotations

  • 1. By
  • 2. Java Annotations • Before the advent of Annotations, you don’t need to define your source code metadata outside in some properties file. • Now, they can directly define this meta-data information in the source code itself. • If used this feature wisely (as it is used in latest java frameworks like Spring and Strutc), benefits are countless.
  • 3. Java Annotations - History • The Java platform has various ad-hoc annotation mechanisms—for example, the transient modifier, or the @deprecated javadoc tag. • JSR-175 introduced the general-purpose annotation (also known as metadata) facility to the Java Community Process in 2002; it gained approval in September 2004. • Annotations became available in the language itself beginning with version 1.5 of the JDK. • The apt tool provided a provisional interface for compile-time annotation processing in JDK version 1.5; JSR-269 formalized this, and it became integrated into the javac compiler in version 1.6.
  • 4. Java Annotations in 5 Steps 1. Annotations are metadata which can be applied on either annotations OR other java element in java source code. 2. 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. 3. Annotations can be read from source files, class files, or reflectively at run time. 4. There are 10 in-built annotations as of today. 5 of them are meant to be applied on custom annotations and other 5 are meant to be applied on java source code elements. 5. Because annotation types are compiled and stored in byte code files just like classes, the annotations returned by these methods can be queried just like any regular Java object.
  • 5. Why annotations? • Introduced in Java in the J2SE update 5 already and the main reason was the need to provide a mechanism that allows programmers to write metadata about their code directly in the code itself. • Before annotations, the way programmers were describing their code was not standardized and each developer did it in his own original way: using transient keywords, via comments, with interfaces, etc. This was not a good approach and a decision was taken: a new form of metadata is going to be available in Java, annotations were introduced.
  • 6. Why annotations? (Contd…) • At that moment, XML was used as standard code configuration mechanism for different type of applications. This was not the best way to do it because of the decoupling between code and XML (XML is not code!) and the future maintenance of this decoupled applications. • There were other reasons like for example the usage of the reserved word “@deprecated” (with small d) in the Javadocs since Java update 4, I am very sure that this was one of the reasons for the current annotations syntax using the “@”.
  • 7. When Not to Use Annotations • Do not over use annotation as it will pollute the code. • It is better not to try to change the behavior of objects using annotations. • There is sufficient constructs available in oops and annotation is not a better mechanism to deal with it. • Do not try to over generalize as it may complicate the underlying code. Code is the real program and annotation is meta. • Avoid using annotation to specify environment / application / database related information.
  • 8. Use cases • Annotations can be used for many different purposes, the most common ones are: 1. Information for the compiler: Annotations can be used by the compiler to produce warnings or even errors based on different rules. One example of this kind of usage is the Java 8 @Functional Interface annotation. This one makes the compiler to validate the annotated class and check if it is a correct functional interface or not. 2. Documentation: Annotations can be used by software applications to measure the quality of the code like Find Bugs or PMD do or generate reports automatically like Jenkins, Jira or Team city. 3. Code generation: annotations can be used to generate code or XML files automatically using metadata information present in the code. A good example of this is the JAXB library. 4. Runtime processing: Annotations that are examined in runtime can be used for different objectives like unit testing (Junit), dependency injection (Spring), validation, logging (Log4J) ,data access (Hibernate) etc.
  • 9. Annotation Structure • There are two main components in annotations. 1. First is annotation type 2. Second is the annotation itself which we use in the code to add meaning. • Every annotation belongs to a annotation type.
  • 10. Annotation Type • Annotation type is very similar to an interface with little difference. 1. We attach ‘@’ just before interface keyword. 2. Methods will not have parameters. 3. Methods will not have throws clause. 4. Method return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. 5. We can assign a default value to method. @interface { method declaration; }
  • 11. Meta Annotations • Annotations itself is meta information then what is meta annotations? It is information about annotation. • When we annotate a annotation type then it is called meta annotation. • For example, we say that this annotation can be used only for methods. @Target(ElementType.METHOD) public @interface MethodInfo { }
  • 12. Annotation Types • Documented When a annotation type is annotated with @Documented then wherever this annotation is used those elements should be documented using Javadoc tool. import java.lang.annotation.Documented; @Documented public @interface MyAnnotation { } @MyAnnotation public class MySuperClass { ... } When generating JavaDoc for the MySuperClass class, the @MyAnnotation is now included in the JavaDoc.
  • 13. Annotation Types (Contd…) • @Inherited The @Inherited annotation signals that a custom Java annotation used in a class should be inherited by subclasses inheriting from that class. Here is an @Inherited Java annotation example: java.lang.annotation.Inherited @Inherited public @interface MyAnnotation { } @MyAnnotation public class MySuperClass { ... } public class MySubClass extends MySuperClass { ... } The class MySubClass inherits the annotation @MyAnnotation because MySubClass inherits from MySuperClass, and MySuperClass has a @MyAnnotation annotation.
  • 14. Annotation Types (Contd…) • @Target You can specify which Java elements your custom annotation can be used to annotate. You do so by annotating your annotation definition with the @Target annotation. import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target({ElementType.METHOD}) public @interface MyAnnotation { String value(); } This example shows a Java annotation that can only be used to annotate methods.
  • 15. Annotation Types (Contd…) • @Target (Contd…) • The ElementType class contains the following possible targets: • ElementType.ANNOTATION_TYPE • ElementType.CONSTRUCTOR • ElementType.FIELD • ElementType.LOCAL_VARIABLE • ElementType.METHOD • ElementType.PACKAGE • ElementType.PARAMETER • ElementType.TYPE The ANNOTATION_TYPE target means Java annotation definitions. Thus, the annotation can only be used to annotate other annotations. Like the @Target and @Retention annotations. The TYPE target means any type. A type is either a class, interface, enum or annotation.
  • 16. Annotation Types (Contd…) • @Target (Contd…) : A Typical Implementation of @Target @Target({ElementType.TYPE,ElementType.METHOD, ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE, ElementType.PACKAGE,ElementType.FIELD,ElementType.LOCAL_VARIABLE})
  • 17. Annotation Types (Contd…) • @Retention You can specify for your custom annotation if it should be available at runtime, for inspection via reflection. You do so by annotating your annotation definition with the @Retention annotation. Here is how that is done: import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation { String value() default ""; } Runtime The value name itself says, when the retention value is ‘Runtime’ this annotation will be available in JVM at runtime. We can write custom code using reflection package and parse the annotation.
  • 18. Annotation Types (Contd…) • @Retention (Contd…) • The RetentionPolicy class contains two more values you can use: 1. RetentionPolicy.CLASS means that the annotation is stored in the .class file, but not available at runtime. This is the default retention policy. 2. RetentionPolicy.SOURCE This annotation will be removed at compile time and will not be available at compiled class.
  • 19. Java Annotation Purposes • Java annotations are typically used for the following purposes: 1. Compiler instructions 2. Build-time instructions 3. Runtime instructions
  • 20. Built-in Java Annotations • Java comes with three built-in annotations which are used to give the Java compiler instructions. 1. @Deprecated 2. @Override 3. @SuppressWarnings
  • 21. @Deprecated • Used to mark a class, method or field as deprecated, meaning it should no longer be used. • If your code uses deprecated classes, methods or fields, the compiler will give you a warning. • Example: @Deprecated public class MyComponent { } You can also use the @Deprecated annotation above method and field declarations, to mark the method or field as deprecated.
  • 22. @Override • Used above methods that override methods in a superclass. • If the method does not match a method in the superclass, the compiler will give you an error. • The @Override annotation is not necessary in order to override a method in a superclass. • It is a good idea to use it still, though. In case someone changed the name of the overridden method in the superclass, your subclass method would no longer override it. • With the @Override annotation the compiler would tell you that the method in the subclass is not overriding any method in the superclass.
  • 23. @Override (Contd…) Example: public class Super_Class { public void doTheThing() { System.out.println("Do the thing"); } } public class Sub_Class extends Super_Class{ @Override public void doTheThing() { System.out.println("Do it differently"); } } “In case the method doTheThing() in Super_Class changes signature so that the same method in the subclass no longer overrides it, the compiler will generate an error.”
  • 24. @Override (Contd…) package Annot; class ParentClass { public void displayMethod(String msg){ System.out.println(msg); } } class SubClass extends ParentClass { @Override public void displayMethod(String msg){ System.out.println("Message is: "+ msg); } public static void main(String args[]){ SubClass obj = new SubClass(); obj.displayMethod("Hey!!"); } } Output: Message is: Hey!!
  • 25. Why we use @Override annotation 1. If programmer makes any mistake such as wrong method name, wrong parameter types while overriding, you would get a compile time error. As by using this annotation you instruct compiler that you are overriding this method. If you don’t use the annotation then the sub class method would behave as a new method (not the overriding method) in sub class. 2. It improves the readability of the code. So if you change the signature of overridden method then all the sub classes that overrides the particular method would throw a compilation error, which would eventually help you to change the signature in the sub classes. If you have lots of classes in your application then this annotation would really help you to identify the classes that require changes when you change the signature of a method.
  • 26. @SuppressWarnings • Makes the compiler suppress warnings for a given method. • For instance, if a method calls a deprecated method, or makes an insecure type cast, the compiler may generate a warning. • You can suppress these warnings by annotating the method containing the code with the @SuppressWarnings annotation. • Example: @SuppressWarnings public void methodWithWarning() { }
  • 27. @SuppressWarnings (Contd…) package Annot; public class Supress { @Deprecated public void showDeprecatedMessage(){ System.out.println("This method is marked as deprecated"); } @SuppressWarnings("deprecation") public static void main(String a[]){ Supress spw = new Supress(); spw.showDeprecatedMessage(); } } Output: This method is marked as deprecated
  • 28. Categories of annotations • Marker annotations have no variables. The annotation simply appears, identified by name, with no additional data supplied. The @Override and @Deprecated are marker annotations. For example, @MarkerAnnotation is a marker annotation. It includes no data, just the annotation name.
  • 29. Categories of annotations(Contd…) • Single-value annotations are similar to markers, but provide a single piece of data. Because only a single bit of data is supplied. • An annotation that has one method, is called single-value annotation. • Example: • The code to apply the single value annotation @interface MyAnnotation{ int value() default 0; } @MyAnnotation(value=10)
  • 30. Categories of annotations(Contd…) • Full annotations have multiple data members. As a result, you must use a fuller syntax @FullAnnotation(var1="data value 1", var2="data value 2", var3="data value 3")
  • 31. Custom Annotations To create a custom annotation, you must use the keyword “@interface“. Other important things to remember while creating custom annotations are listed below: • Each method declaration defines an element of the annotation type. • Method declarations must not have any parameters or a throws clause. • Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. • Methods can have default values.
  • 32. Custom Annotations (Contd…) package Custom.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface customFile1 { String author() default "unknown"; String version() default "0.0"; } package Custom.Annotation; @customFile1 public class CustomClass1 { @customFile1(author = "Anjum", version = "1.0") public String getString() { return null; } }
  • 33. Custom Annotations (Contd…) package Custom.Annotation; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; public class MainClass { public static void main(String[] args) throws NoSuchMethodException, SecurityException { new CustomClass1(); Class<CustomClass1> cc1 = CustomClass1.class; readAnnotationOn(cc1); Method method = cc1.getMethod("getString", new Class[]{}); readAnnotationOn(method); }
  • 34. Custom Annotations (Contd…) static void readAnnotationOn(AnnotatedElement element){ try { System.out.println("n Finding annotations on " + element.getClass().getName()); Annotation[] annotations = element.getAnnotations(); for (Annotation annotation : annotations){ if (annotation instanceof customFile1) { customFile1 cf1 = (customFile1) annotation; System.out.println("Author :" + cf1.author()); System.out.println("Version :" + cf1.version()); } } } catch (Exception e) { e.printStackTrace();}}}
  • 35. Custom Annotations (Contd…) Output: Finding annotations on java.lang.Class Author :unknown Version :0.0 Finding annotations on java.lang.reflect.Method Author :Anjum Version :1.0
  • 36. Fetching Annotation Info • Reflection API can be used to explore the Annotation details at runtime programmatically . • Syntax: isAnnotationPresent()
  • 37. Fetching Annotation Info (Contd…) • Example: package Annot; public class IsAnnotPres { public static void main(String[] unused) { try { String n = "java.lang.Deprecated"; Class c = Class.forName(n); Class d = Class.forName("java.util.Date"); System.out.println("Status of Annotation: " +d.isAnnotationPresent(c)); } catch (Exception ex) { ex.printStackTrace(); } } } Output: Status of Annotation: false
  • 38. Annotations applied to Java code: • @Override - Checks that the method is an override. Causes a compile error if the method is not found in one of the parent classes or implemented interfaces. • @Deprecated - Marks the method as obsolete. Causes a compile warning if the method is used. • @SuppressWarnings - Instructs the compiler to suppress the compile time warnings specified in the annotation parameters. • @SafeVarargs - Suppress warnings for all callers of a method or constructor with a generics varargs parameter, since Java 7. • @FunctionalInterface - Specifies that the type declaration is intended to be a functional interface, since Java 8.
  • 39. Annotations applied to other annotations (also known as "Meta Annotations"): • @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. • @Target - Marks another annotation to restrict what kind of Java elements the annotation may be applied to. • @Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses). • @Repeatable - Specifies that the annotation can be applied more than once to the same declaration, since Java 8.