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

An alternative tutorial to the Java Docs

Random SO Question on Annotations 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.

This tutorial by Rick Hightower was awesome article on CDI Dependency Injection.

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;

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() )

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


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s