Вы находитесь на странице: 1из 17

Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

HowToDoInJava

Interview Questions Popu lar Guides Core J ava More Topics

Annotations / Complete Java Annotations Tutorial


    

ava Annotations Tutorial


An annotation is a kind of meta data
Be Awesome When It Matters !!
in java which can be applied at
various elements of java sourcecode Join 4000+ Happy Learners and receive

so that later some tool, debugger or my free ebook "5 Steps Guide for Java
Interview Preparation". This book will
application program can take
help you in taking your interview
advantage of these annotations; and
preparation to next stage, where you will
help analyzing the program in positive
outshine your competitors.
and constructive way. Just to
mention, we can annotate classes,
Sign up to download !!
methods, variables, parameters and
packages in java OR in one word
almost everything. It is important to
learn that the annotations applied on
d into bytecode with other class members, and using re¡ection SUBSCRIBE
meta data information to decide the appropriate action to

ing all important concepts which you should keep handy with
s wonderful feature of java language.

ava Annotations

To Other Annotations

1 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

To Java Code

Rs. 249 Rs. 9 Rs. 125

notations
Rs. 20 Rs. 109 Rs. 60

Using Re¡ection

Rs. 795 Rs. 10 Rs. 99

erview of Java Annotations


troduced as “A Metadata Facility” through JSR 175. The JSR
Rs. 499 Rs. 595 Rs. 19

he Java-TM Programming Language would allow classes,


ethods to be marked as having particular attributes”.
Rs. 89 Rs. 9 Rs. 14

data multiple times. What is this metadata in java language


about them? Let’s understand the need to metadata with an

ass which is declared as  nal:

d in class declaration. And the impact of this declaration is


ass or make a child class of it. How compiler understand
‘ keyword. Right? Well, this is called metadata.

t data. Metadata adds some additional ¡ags on your actual

2 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

he class MyFinalClass), and in runtime either you or JVM


ags, can utilize this metadata information to make
sed on context.

ons to denote metadata. We can annotate classes, interface,


ven packages also. We have to utilize the metadata
these annotations in runtime usually.

ions in Java
our own but java does provide some in-built annotations too
section, we will learn about these in-build annotations and

mportant to remind that annotations are metadata and they


of sourcecode and even on other annotations as well. I will
ions which should be applied on other annotations because it
we start discussing annotations applicable on java

plied To Other Annotations


ve annotations are used inside other annotations to hint
otation should be treated by JVM. Let’s explore these 5

ow the marked annotation is stored in java runtime. Whether it


ly, embedded into the generated class  le, or it will be
ection as well.

Retention;
RetentionPolicy;

3 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

hat new annotation should be included into java documents


t generator tools.

Documented;

notation {

restrict the usage of new annotation on certain java elements


methods. After specifying the targets, you will be able to use
n elements only.

ElementType;

.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR,


.ANNOTATION_TYPE, ElementType.FIELD, ElementType.LOCAL_VARIABLE,
.PACKAGE, ElementType.PARAMETER})
notation {

tion to any other annotation i.e. @MyCustomAnnotation; and


applied of any class MyParentClass then
l be available to all child classes of MyParentClass as well. It
n you try to lookup the annotation @MyCustomAnnotation on
ent classes of X unto n level are queried for
d if annotation is present at any level then result is true, else

annotations applied on parent class are not available to child

Inherited;

notation {

4 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

applied on a java element only once. But, by any requirement,


ion more than once, then use @Repeatable annotation on your

ed in latest java 8 release.

as below:

)
p() { ... }

plied To Java Code


notation which were meant to be applied on other annotations.
-built annotations which are primarily targeted towards java

t the annotated method is overridden method. It causes a


nnotated method is not found in one of the parent classes or
ry useful annotation and I will recommend to use it frequently.

5 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

hods or classes which you need to mark as deprecated. Any


s deprecated class or method, will get a compiler “warning“.

he compiler to suppress the compile time warnings speci ed in


e.g. to ignore the warnings of unused class attributes and
arnings("unused") either for a given attribute or at class level
s and unused methods.

ted options to @SuppressWarnings, please refer to speci c


n. e.g. for Eclipse refer to this complete list of values.

notation ensures that the body of the annotated method or


m potentially unsafe operations on its varargs parameter.
a method or constructor suppresses unchecked warnings
le arity (vararg) type and suppresses unchecked warnings
creation at call sites.

final T... items )

6 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

mark an interface as functional interface which are introduced


functional interfaces please follow the linked post.

tionalInterface {

tions in Java
given examples above are in-built java annotations and you
ourcecode directly. Java allows you to create your own
m annotations. You can create your own annotations for
hem as well. Let’s learn how to do create custom annotations.

m Annotations
ion, you must use the keyword “@interface“. Other important
reating custom annotations are listed below:

 nes an element of the annotation type.


must not have any parameters or a throws clause.
icted to primitives, String, Class, enums, annotations, and
g types.
fault values.

otaion de nitions and their usage can be listed as:

emoAnnotation without any value

7 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

"Gupta")

"[unassigned]";
"[unimplemented]";

Annotations
dea of how annotations should be used in above examples.
detailed example which we can later use in next section where
values through re¡ection.

, I have created one annotation @JavaFileInfo, which has two


. This can be applied on java class, interface, enum OR
lues are provided to if it’s not there then also we print

ElementType;
Retention;
RetentionPolicy;

lementType.METHOD})

8 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

on, all we have to do is to annotate any class/interface of


hor name, and version of  le if any.

, version = "1.0")

e annotations, right?

notations Using Reflection


ed the annotation and then used it. The main reason we are
use they are metadata. So it means we should be able to fetch
annotation information when we need it.

ection API to access annotations on any type (i.e. class or


learn how to do this with an example.

Annotation;
otatedElement;

onExample

tring[] args) throws NoSuchMethodException, SecurityException

lassObj = DemoClass.class;
lassObj);
assObj.getMethod("getString", new Class[]{});

nOn(AnnotatedElement element)

"\n Finding annotations on " + element.getClass().getName());


tions = element.getAnnotations();
otation : annotations)

nstanceof JavaFileInfo)

fileInfo = (JavaFileInfo) annotation;


"Author :" + fileInfo.author());
"Version :" + fileInfo.version());

9 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

lang.Class

lang.reflect.Method

ations, you don’t need to de ne your sourcecode metadata


le. Now, they can directly de ne this meta-data information
used this feature wisely (as it is used in latest java
), bene ts are countless.

g from this post in some bullet points:

data which can be applied on either annotations OR other java

rectly affect program semantics, but they do affect the way


by tools and libraries, which can in turn affect the semantics

ead from source  les, class  les, or re¡ectively at run time.


nnotations as of today. 5 of them are meant to be applied on
and other 5 are meant to be applied on java source code
ctive sections for more details.
ypes are compiled and stored in byte code  les just like
ons returned by these methods can be queried just like any
ou saw an example above.

very powerful feature i.e. Annotation. Let me know of your


nts section.

10 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

nd Tech News for FREE !!!

and receive my free ebook "5 Steps Guide for Java


This book will help you in taking your interview
ge, where you will outshine your competitors.

SUBSCRIBE

okesh Gupta

HowToDoInJava.com in late 2012. I love computers,


ming and solving problems everyday. A family guy with
nd me on Facebook, Twitter and Google Plus.

11 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

015 at 5:19 pm

aFileInfo annotaion in my code on 100 classes then I have to


hen whts the fun in annotaion?

27, 2015 at 5:22 pm

… not data. You would like to process your classes


ons.. there is difference.

5 at 12:31 am

15 at 1:27 pm

ning aboubt java metadata.

12 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

at 5:14 pm

thanks for it…but how to process the class or source

015 at 5:54 pm

5 at 3:41 pm

.thanks Lokesh…

at 6:19 pm

the article.

7:15 pm

s wonderful feature Annotation topic. I need small

13 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

en you write Jersy REST services we use @Path annotation


h should be unique . if we de ne same path twice jersey
nd throws exception . question is : is there any way to catch

14 at 7:29 pm

ompilation is very complex process and JVM does a lot of


validates business rules for any application of framework.
mpossible to validate the duplicate path annotations at
n detect them only in runtime, when class loaders have
n memory for execution.

7:01 am

ection concept and requested about its practical


ply,,,plse sir do complete operation of re¡ection.

14 at 7:30 am

ve missed your previous request. Please allow me some time


ection is on top priority.

14 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

5, 2014 at 7:30 pm

java.com/2014/06/12/real-usage-examples-of-re¡ection-

5:33 am

s article ….

& Share Feedback


be published. Required  elds are marked *

ts? Please use [java] ... [/java] tags otherwise code may not

15 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

Search Tutorials

Recommended

10 Life Lessions
Generate Secure Passwords
How Web Servers work?
How Java I/O Works Internally?
5 Class Design Principles
Unit Testing Best Practices
Exception Handling Best Practices
Best Way to Learn Java
Java Best Practices
Java Interview Questions
Best Java Books

Developer Tools

16 of 17 3/5/2016 6:07 PM
Complete Java Annotations Tutorial - HowToDoInJava http://howtodoinjava.com/core-java/annotations/complete-java-annotation...

JSON Formatter and Mini er


XML Formatter and Mini er
CSS Formatter and Mini er
HTML Formatter and Mini er

Be Informed And Stay Updated !!

Join 4000+ Happy Learners and receive my free ebook


"5 Steps Guide for Java Interview Preparation". This
book will help you in taking your interview preparation to
next stage, where you will outshine your competitors.

Sign up to download !!

SUBSCRIBE

References Meta Links

Oracle Java Docs Advertise


Spring 3 Reference Contact Us
Spring 4 References Privacy policy
Jboss RESTEasy JAX-RS About Me
Hibernate Developer Guide Online tests
Junit Wiki
Maven FAQs
Dzone Dev Links
JSP Homepage
ANT Homepage

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved

17 of 17 3/5/2016 6:07 PM

Вам также может понравиться