Over a million developers have joined DZone.

Annotations in Java

DZone's Guide to

Annotations in Java

Annotations and reflection work hand-in-hand in Java. This tutorial demonstrates creating a custom annotation.

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

Annotations in Java provide a means to describe classes, fields, and methods. Essentially, they are a form of metadata added to a Java source file, they can’t affect the semantics of a program directly. However, annotations can be read at run-time using Reflection & this process is known as Introspection. Then it could be used to modify classes, fields, or methods.

This feature is often exploited by Libraries & SDKs (hibernate, JUnit, Spring Framework) to simplify or reduce the amount of code that a programmer would otherwise do in order to work with these Libraries or SDKs.Therefore, it’s fair to say Annotations and Reflection work hand-in hand in Java.

We also get to limit the availability of an annotation to either compile-time or runtime. Below is a simple example on creating a custom annotation

01. Driver.java

package io.hamzeen;

import java.lang.annotation.Annotation;

public class Driver {

public static void main(String[] args) {
Class<TestAlpha> obj = TestAlpha.class;
if (obj.isAnnotationPresent(IssueInfo.class)) {

Annotation annotation = obj.getAnnotation(IssueInfo.class);
IssueInfo testerInfo = (IssueInfo) annotation;

System.out.printf("%nType: %s", testerInfo.type());
System.out.printf("%nReporter: %s", testerInfo.reporter());
System.out.printf("%nCreated On: %s%n%n",

02. TestAlpha.java

package io.hamzeen;

import io.hamzeen.IssueInfo;
import io.hamzeen.IssueInfo.Type;

@IssueInfo(type = Type.IMPROVEMENT, reporter = "Hamzeen. H.")
public class TestAlpha {


03. IssueInfo.java

package io.hamzeen;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

 * @author Hamzeen. H.
 * @created 10/01/2015
 * TestInfo annotation definition
public @interface IssueInfo {

public enum Type {

Type type() default Type.BUG;

String reporter() default "Vimesh";

String created() default "10/01/2015";

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

design pattens ,java

Published at DZone with permission of Hamzeen Hameem, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}