以下是一个简单的annotation示例 :
package org.codespace.annotation.test;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author ykc
*
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented()
public @interface SayHello
{
String value() default "HELLO WORLD";
}
package org.codespace.annotation.test;
/**
*
* @author ykc
*
*/
@SayHello()
public class HelloWorld
{
public void show()
{
System.out.println("+++++++++++++++++");
}
}
package org.codespace.annotation.test;
/**
*
* @author ykc
*
*/
public class TestHelloWorld
{
@SuppressWarnings("unchecked")
public static void main(String[] args) throws ClassNotFoundException
{
Class cls = Class.forName("org.codespace.annotation.test.HelloWorld");
boolean bool = cls.isAnnotationPresent(SayHello.class);
if (bool)
{
SayHello hello = (SayHello) cls.getAnnotation(SayHello.class);
System.out.println("打招呼");
System.out.println(hello.value());
System.out.println("完毕");
}
}
}