You are on page 1of 9

06/11/2016

Java Custom Annotations Example

Java Custom Annotations Example


By mkyong (https://www.mkyong.com/author/mkyong/) | January 3, 2014 | Viewed : 296,441 times +2,764 pv/w

In this tutorial, we will show you how to create two custom annotations @Test and @TestInfo , to simulate a simple unit test framework.
P.S This unit test example is inspired by this official Java annotation article (http://docs.oracle.com/javase/1.5.0/docs/guide/language/annotations.html).

1. @Test Annotation
This @interface tells Java this is a custom annotation. Later, you can annotate it on method level like this @Test(enable=false) .
Test.java
package com.mkyong.test.core;
import
import
import
import

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) //can use in method only.
public @interface Test {
//should ignore this test?
public boolean enabled() default true;
}

Note
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.

Java APIs for Developers

2. @TesterInfo Annotation
This @TesterInfo is applied on class level, store the tester details. This shows the different use of return types enum, array and string.

https://www.mkyong.com/java/java-custom-annotations-example/

1/9

06/11/2016

Java Custom Annotations Example

TesterInfo.java
package com.mkyong.test.core;
import
import
import
import

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) //on class level
public @interface TesterInfo {
public enum Priority {
LOW, MEDIUM, HIGH
}
Priority priority() default Priority.MEDIUM;
String[] tags() default "";
String createdBy() default "Mkyong";
String lastModified() default "03/01/2014";
}

3. Unit Test Example


Create a simple unit test example, and annotated with the new custom annotations @Test and @TesterInfo .
TestExample.java
package com.mkyong.test;
import com.mkyong.test.core.Test;
import com.mkyong.test.core.TesterInfo;
import com.mkyong.test.core.TesterInfo.Priority;
@TesterInfo(
priority = Priority.HIGH,
createdBy = "mkyong.com",
tags = {"sales","test" }
)
public class TestExample {
@Test
void testA() {
if (true)
throw new RuntimeException("This test always failed");
}
@Test(enabled = false)
void testB() {
if (false)
throw new RuntimeException("This test always passed");
}
@Test(enabled = true)
void testC() {
if (10 > 1) {
// do nothing, this test always passed.
}
}
}

4. Java reflection Read the Annotation


https://www.mkyong.com/java/java-custom-annotations-example/

2/9

06/11/2016

Java Custom Annotations Example

4. Java reflection Read the Annotation


Below example show you how to use Java reflection APIs to read and process the custom annotations.
RunTest.java

https://www.mkyong.com/java/java-custom-annotations-example/

3/9

06/11/2016

Java Custom Annotations Example

package com.mkyong.test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import com.mkyong.test.core.Test;
import com.mkyong.test.core.TesterInfo;
public class RunTest {
public static void main(String[] args) throws Exception {
System.out.println("Testing...");
int passed = 0, failed = 0, count = 0, ignore = 0;
Class<TestExample> obj = TestExample.class;
// Process @TesterInfo
if (obj.isAnnotationPresent(TesterInfo.class)) {
Annotation annotation = obj.getAnnotation(TesterInfo.class);
TesterInfo testerInfo = (TesterInfo) annotation;
System.out.printf("%nPriority :%s", testerInfo.priority());
System.out.printf("%nCreatedBy :%s", testerInfo.createdBy());
System.out.printf("%nTags :");
int tagLength = testerInfo.tags().length;
for (String tag : testerInfo.tags()) {
if (tagLength > 1) {
System.out.print(tag + ", ");
} else {
System.out.print(tag);
}
tagLength--;
}
System.out.printf("%nLastModified :%s%n%n", testerInfo.lastModified());
}
// Process @Test
for (Method method : obj.getDeclaredMethods()) {
// if method is annotated with @Test
if (method.isAnnotationPresent(Test.class)) {
Annotation annotation = method.getAnnotation(Test.class);
Test test = (Test) annotation;
// if enabled = true (default)
if (test.enabled()) {
try {
method.invoke(obj.newInstance());
System.out.printf("%s - Test '%s' - passed %n", ++count, method.getName());
passed++;
} catch (Throwable ex) {
System.out.printf("%s - Test '%s' - failed: %s %n", ++count, method.getName(), ex.getCause());
failed++;
}
} else {
System.out.printf("%s - Test '%s' - ignored%n", ++count, method.getName());
ignore++;
}
}
}
System.out.printf("%nResult : Total : %d, Passed: %d, Failed %d, Ignore %d%n", count, passed, failed, ignore);
}
}

https://www.mkyong.com/java/java-custom-annotations-example/

4/9

06/11/2016

Java Custom Annotations Example

Output
Testing...
Priority :HIGH
CreatedBy :mkyong.com
Tags :sales, test
LastModified :03/01/2014
1 - Test 'testA' - failed: java.lang.RuntimeException: This test always failed
2 - Test 'testC' - passed
3 - Test 'testB' - ignored
Result : Total : 3, Passed: 1, Failed 1, Ignore 1

Done.

References
1.
2.
3.
4.

Wikipedia : Java annotation (http://en.wikipedia.org/wiki/Java_annotation)


Oracle JavaSE docs annotations (http://docs.oracle.com/javase/1.5.0/docs/guide/language/annotations.html)
ElementType JavaDoc (http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/ElementType.html)
RetentionPolicy JavaDoc (http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html)

Tags : annotation (https://www.mkyong.com/tag/annotation/)

unit test (https://www.mkyong.com/tag/unit-test/)

Share this article on


Twitter (https://twitter.com/intent/tweet?text=Java Custom Annotations Example&url=https://www.mkyong.com/java/java-custom-annotationsexample/&via=mkyong)
Facebook (https://www.facebook.com/sharer/sharer.php?u=https://www.mkyong.com/java/java-custom-annotationsexample/) Google+ (https://plus.google.com/share?url=https://www.mkyong.com/java/java-custom-annotations-example/)

Related Posts
218k

How to run unit test with Maven (/maven/how-to-run-unit-test-with-maven/)

416k

Maven + (Spring + Hibernate) Annotation + MySql Example (/spring/maven-spring-hibernate-annotation-mysql-example/)

285k

JUnit 4 Vs TestNG - Comparison (/unittest/junit-4-vs-testng-comparison/)

6k

Logback - Disable logging in Unit Test (/logging/logback-disable-logging-in-unit-test/)

311k

JUnit Tutorial (/tutorials/junit-tutorials/)

310k

Spring MVC form handling annotation example (/spring-mvc/spring-mvc-form-handling-annotation-example/)

404k

Spring AOP + AspectJ annotation example (/spring3/spring-aop-aspectj-annotation-example/)

64k

Spring Batch unit test example (/spring-batch/spring-batch-unit-test-example/)

69k

NoSuchBeanDefinitionException : No qualifying bean of type JobLauncherTestUtils (/spring-batch/nosuchbeandefinitionexception-no-qualifying-bean-oftype-joblaunchertestutils/)

21k

Gradle - How to skip unit test (/gradle/gradle-how-to-skip-unit-test/)

https://www.mkyong.com/java/java-custom-annotations-example/

5/9

06/11/2016

Java Custom Annotations Example

Top 8 Java People You


Should Know

Top 20 Java Websites

Spring Security Hello World


Annotation Example

TestNG Groups Test

Spring AOP + AspectJ


annotation example

Java Custom Exception


Examples

Hibernate save image into


database

TestNG Run multiple test


classes (suite test)

About the Author


mkyong
Founder of Mkyong.com (http://mkyong.com) and HostingCompass.com (http://hostingcompass.com), love Java and open source
stuff. Follow him on Twitter (https://twitter.com/mkyong), or befriend him on Facebook (http://www.facebook.com/java.tutorial) or
Google Plus (https://plus.google.com/110948163568945735692?rel=author). If you like my tutorials, consider make a donation to
these charities (http://www.mkyong.com/blog/donate-to-charity/).

Popular Posts
945k

JAX-WS Tutorial (/tutorials/jax-ws-tutorials/)


1m

How to write to file in Java - BufferedWriter (/java/how-to-write-to-file-in-java-bufferedwriter-example/)


803k

How to convert String to Date - Java (/java/how-to-convert-string-to-date-java/)


639k

Android custom dialog example (/android/android-custom-dialog-example/)


600k

Tomcat - java.lang.OutOfMemoryError: PermGen space (/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/)


921k

JAXB hello world example (/java/jaxb-hello-world-example/)


957k

Android spinner (drop down list) example (/android/android-spinner-drop-down-list-example/)


639k

Spring Auto-Wiring Beans with @Autowired annotation (/spring/spring-auto-wiring-beans-with-autowired-annotation/)


1.4m

Hibernate Tutorial (/tutorials/hibernate-tutorials/)


737k

Spring 3 MVC hello world example (/spring3/spring-3-mvc-hello-world-example/)


855k

JavaMail API - Sending email via Gmail SMTP example (/java/javamail-api-sending-email-via-gmail-smtp-example/)


639k

Jersey hello world example (/webservices/jax-rs/jersey-hello-world-example/)


715k

What is Tomcat default administrator password ? (/tomcat/tomcat-default-administrator-password/)


689k

How to install Maven on Windows (/maven/how-to-install-maven-in-windows/)


619k

https://www.mkyong.com/java/java-custom-annotations-example/

6/9

06/11/2016

Java Custom Annotations Example

Java JSON Tutorial (/tutorials/java-json-tutorials/)


1.4m

Java Properties file examples (/java/java-properties-file-examples/)


878k

Maven Tutorial (/tutorials/maven-tutorials/)


585k

How to get current timestamps in Java (/java/how-to-get-current-timestamps-in-java/)


601k

Spring Security Custom Login Form Example (/spring-security/spring-security-form-login-example/)


724k

Java Date and Calendar examples (/java/java-date-and-calendar-examples/)

Comments
13 Comments

Mkyong.com

Recommend 2

Share

Login

Sort by Best

Join the discussion


Jan Vladimir Mostert 3 years ago

Can you do the same tutorial using AspectJ ?


11

Reply Share

wade 2 years ago

good example simple but clear, thanks


1

Reply Share

Ewen Mackenzie 10 months ago

simply spectacular :D
Reply Share
Kiran Biliyawala a year ago

Simple and Neat .. (Y)


Reply Share
Pradeesh P a year ago

I have a doubt can we do the package level annoatation without adding the adpaters and package-info.java in the same package.
Real Qstn is :
I have different packages around 20 packges which has to use this annotations. so is it neccessery to put adpaters as well as package-info.java in each and
every package. Is there any alternate way for it? please help...
Reply Share
Roman a year ago

Thanks, good explanation


Reply Share
AZiza Saber a year ago

hi friends; how can I read fields , methods ,... of a class by using annotations
thanks
thanks
Reply Share
Jeeva 2 years ago

Hi, do you have sample of initialize a object through annotation


http://stackoverflow.com/quest...
Reply Share
Murali Mohan 2 years ago

Good one... Annotations demystified largely.


Reply Share
Viacheslav Horobchenko 2 years ago

I created a custom method_annotation that allows me to change the order of parts of text in toString() method.
Is it possible to annotate a method before call it (beyond a class definition)?

https://www.mkyong.com/java/java-custom-annotations-example/

7/9

06/11/2016

Java Custom Annotations Example

Is it possible to annotate a method before call it (beyond a class definition)?


Here is an expected code:

System.out.println("Person: " + person.@ToStringOrder(non-default-parameter) toString() );


How to annotate person.toString() ?
What is the correct syntax if it possible?
Thanks in advance
Reply Share
amaresh 2 years ago

is it possible to write a custom annotaion which will set a default value to a java bean variable. for example if there is a list and the getter method should be
initialised to a new arraylist through a custom annotation. can some one suggest.
Reply Share
denuwanthi 2 years ago

very helpful. thanks


Reply Share
Fr Jeremy 2 years ago

This:
Annotation annotation = obj.getAnnotation(TesterInfo.class);
TesterInfo testerInfo = (TesterInfo) annotation;
...can simply be written as:
TesterInfo testerInfo = obj.getAnnotation(TesterInfo.class);
It is not necessary to assign to an intermediate variable of type "Annotation" and then downcast it at runtime - the Java Generics mechanism already handles
the type conversion for you at compile time.
Reply Share

ALSO ON MKYONG.COM

Logback Disable logging in Unit Test

Java 8 Convert Map to List

4 comments 9 months ago

1 comment 3 months ago

Avat fmpdmb That really doesn't make any sense and is not my experience.

Avat Caleb Cushing why are you recommending what's probably the most
verbose and slowest way possible?, map.keySet() returns a Set fand
map.values() return a

You will only see the logback debug loggging if you have that debug
property set or are

MySQL Backup and restore a database or table

Java 8 How to sort a Map

2 comments 3 months ago

3 comments 3 months ago

Avat Savani Hello Mkyong - Could you please also create tutorials for Spring
Boot ? That will help all your followers.

Avat Conor Wow this is very powerful! Can you comment on the time
complexity required to do such an operation? Your code is pretty selfexplanatory but I am unsure about

Subscribe

Add Disqus to your site Add Disqus Add

Privacy

https://www.mkyong.com/java/java-custom-annotations-example/

8/9

06/11/2016

Java Custom Annotations Example

Mkyong
51,636 likes

Like Page

Sign Up

Be the first of your friends to like this

https://www.mkyong.com/java/java-custom-annotations-example/

9/9

You might also like