Java Annotations provides information about the code. Java annotations have no direct effect on the code they annotate. In java annotations tutorial, we will look into the following;
Java 1.5 introduced annotations and now it’s heavily used in Java EE frameworks like Hibernate, Jersey, and Spring. Java Annotation is metadata about the program embedded in the program itself. It can be parsed by the annotation parsing tool or by the compiler. We can also specify annotation availability to either compile time only or till runtime. Before java annotations, program metadata was available through java comments or by Javadoc but annotation offers more than that. Annotations metadata can be available at runtime too and annotation parsers can use it to determine the process flow. For example, in Jersey webservice we add PATH annotation with URI string to a method and at runtime, jersey parses it to determine the method to invoke for given URI pattern.
Creating custom annotation is similar to writing an interface, except that the interface keyword is prefixed with _@_ symbol. We can declare methods in annotation. Let’s see java custom annotation example and then we will discuss its features and important points.
package com.journaldev.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodInfo{
String author() default "Pankaj";
String date();
int revision() default 1;
String comments();
}
Some important points about java annotations are:
There are five types of meta annotations:
Java Provides five built-in annotations.
@Override
- When we want to override a method of Superclass, we should use this annotation to inform compiler that we are overriding a method. So when superclass method is removed or changed, compiler will show error message. Learn why we should always use java override annotation while overriding a method.@Deprecated
- when we want the compiler to know that a method is deprecated, we should use this annotation. Java recommends that in javadoc, we should provide information for why this method is deprecated and what is the alternative to use.@SuppressWarnings
- This is just to tell compiler to ignore specific warnings they produce, for example using raw types in java generics. It’s retention policy is SOURCE and it gets discarded by compiler.@FunctionalInterface
- This annotation was introduced in Java 8 to indicate that the interface is intended to be a functional interface.@SafeVarargs
- A programmer assertion that the body of the annotated method or constructor does not perform potentially unsafe operations on its varargs parameter.Let’s see a java example showing the use of built-in annotations in java as well as the use of custom annotation created by us in the above example.
package com.journaldev.annotations;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class AnnotationExample {
public static void main(String[] args) {
}
@Override
@MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 1)
public String toString() {
return "Overriden toString method";
}
@Deprecated
@MethodInfo(comments = "deprecated method", date = "Nov 17 2012")
public static void oldMethod() {
System.out.println("old method, don't use it.");
}
@SuppressWarnings({ "unchecked", "deprecation" })
@MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 10)
public static void genericsTest() throws FileNotFoundException {
List l = new ArrayList();
l.add("abc");
oldMethod();
}
}
I believe above java annotation example is self-explanatory and showing the use of annotations in different cases.
We will use Reflection to parse java annotations from a class. Please note that Annotation Retention Policy should be RUNTIME otherwise its information will not be available at runtime and we won’t be able to fetch any data from it.
package com.journaldev.annotations;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class AnnotationParsing {
public static void main(String[] args) {
try {
for (Method method : AnnotationParsing.class.getClassLoader()
.loadClass(("com.journaldev.annotations.AnnotationExample")).getMethods()) {
// checks if MethodInfo annotation is present for the method
if (method.isAnnotationPresent(com.journaldev.annotations.MethodInfo.class)) {
try {
// iterates all the annotations available in the method
for (Annotation anno : method.getDeclaredAnnotations()) {
System.out.println("Annotation in Method '" + method + "' : " + anno);
}
MethodInfo methodAnno = method.getAnnotation(MethodInfo.class);
if (methodAnno.revision() == 1) {
System.out.println("Method with revision no 1 = " + method);
}
} catch (Throwable ex) {
ex.printStackTrace();
}
}
}
} catch (SecurityException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output of the above program is:
Annotation in Method 'public java.lang.String com.journaldev.annotations.AnnotationExample.toString()' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=1, comments=Main method, date=Nov 17 2012)
Method with revision no 1 = public java.lang.String com.journaldev.annotations.AnnotationExample.toString()
Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.oldMethod()' : @java.lang.Deprecated()
Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.oldMethod()' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=1, comments=deprecated method, date=Nov 17 2012)
Method with revision no 1 = public static void com.journaldev.annotations.AnnotationExample.oldMethod()
Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.genericsTest() throws java.io.FileNotFoundException' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=10, comments=Main method, date=Nov 17 2012)
Reflection API is very powerful and used widely in Java, J2EE frameworks like Spring, Hibernate, JUnit, check out Reflection in Java. That’s all for the java annotations example tutorial, I hope you learned something from it. Java Annotations Updates:
Reference: Oracle website
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev
I see way too much fun with annotations (including Oracle flaky documentation that cannot stay focused on bulletpoints on the subject). Can we have in simple points steps to create annotation and process it required by Java with simplest example and no funky games with processors, testers and who-knows-what? I mean it is good to know it, but that’s next after we become proficient… especially when in commercial programming we do not play in academic way - not time for this fun, we program for living according to certain steps that are supposed to help simplicity and not scientific complexity (maintiainable code principle).
- Anonymous
… and I meant on the subject “CUSTOM annotation creation” not standard/built-in usage (that we know and there is no need for documentation that is on Oracle website). I have learned not much here. I know how to use annotations, reflection and write main method with some System printouts. It would be much more useful to explain and show how custom annotation gets processed and write for example custom annotation that create a proxy method or sets a value on annotated variable. So called “one-liner-focused-example”.
- Anonymous
Could you tell me the difference between these below code List list=new ArrayList(); ArrayList list=new ArrayList(); When to use this. Cold you provide real time examples on this.
- Siddu
Hi Pankaj, your tutorial is really nice.I have one doubt,In the class AnnotationExample.java, we have 3 methods,1. toString() 2.oldMethod() 3.genericsTest(), and all these methods have 2 annotations, but during parsing in AnnotationParsing.java , we are getting 2 annotations for oldMethod() and 1 annotation for toString() as well as genericsTest(). do we have any reason for missing @override and @suppresswarnings in the output?
- Vijay
hi pankaj how i can search custom annotation for method in java source code?i am parsing all java classes .i want method name that have some custom annotation .can you please help me??if possible put some example to search custom annotation in java code
- dhaval
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.