Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

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",
testerInfo.created());
}
}
}

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
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IssueInfo {

public enum Type {
BUG, IMPROVEMENT, FEATURE
}

Type type() default Type.BUG;

String reporter() default "Vimesh";

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


Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}