Java Annotation Example

Categories: Java June 22nd, 2014 19:44

Annotation

package com.liguoliang.lang;

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

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})

/**
 * http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html
 * @author Guoliang
 *
 */
public @interface Note {
	String title() default "Note";
	String details();
}

Usage


package com.test.meta;

import static org.junit.Assert.*;

import org.junit.Test;

import com.liguoliang.lang.Note;

@Note(details="This test is for Annotation")
public class TestMeta {

	@Test
	public void test() {
		
		Class klass = TestMeta.class;

		assertTrue(klass.isAnnotationPresent(Note.class));
		
		Note note =  klass.getAnnotation(Note.class);
		System.out.println("Class: " + klass.getCanonicalName() + "Note: " + note.title() + ": " + note.details());
	}

}


Output:

Class: com.test.meta.TestMetaNote: Note: This test is for Annotation

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.