Annotations in Java

Annotations in Java are normally used to comment code or to store data. There a lot more you can do with them but this is just another dumb skeleton code example.

Here are some resources that you might find helpful to learn more about Annotations, some more helpful than others.

Java Docs
http://docs.oracle.com/javase/tutorial/java/javaOO/annotations.html

An alternative tutorial to the Java Docs
http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm

Random SO Question on Annotations in Java
http://stackoverflow.com/questions/5685795/help-me-understanding-annotation-in-java

This is a tutorial by Jakob Jenkov was a great read. It was written for Java 5 but it carries over to 6 and 7.
http://tutorials.jenkov.com/java-reflection/annotations.html

This tutorial by Rick Hightower was awesome article on CDI Dependency Injection.
http://java.dzone.com/articles/cdi-di-p2


Coding an annotation is very much like writing an interface. You don’t define the values, just reference them. In this case I set the retention policy to run time, you might not necessary need set a retention policy in your own annotation.

package Annotations;

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

@Retention(RetentionPolicy.RUNTIME)
public @interface School {
	public String name();
	public String state();
}

Next, lets put this somewhere in a object, I made a simply Student object to try this out.

package Annotations;

@School(name = "Davenport", state = "MI")
class Student {
	private String major;
		
	public Student(String major){
		this.major = major;
	}
}

Finally, here is a test script I made to show how you can iterate through annotations.

package Annotations;

import java.lang.annotation.Annotation;

public class testStudent {

	public static void main(String[] args) {	
		Student dan = new Student("Nerd");
		
		for(Annotation annot : dan.getClass().getAnnotations() )
			System.out.println(annot.toString());
	}	
}

Sample Output:
@Annotations.School(name=Davenport, state=MI)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s