1.
@interface Annotation 名称 {
返回类型method1() [default返回值];
}
方法必须是无参数,无异常抛出。方法定义了annotation的成员,方法名成为了成员名,方法返回值成为了成员的类型
2.
原注解
@Retention(SOURCE/CLASS/RUNTIME)
SOURCE:注解信息在编译阶段被丢弃,仅保留在java文件中
CLASS:注解信息保留在编译文件中,运行阶段不存在
RUNTIME:保留在运行阶段
@Target({TYPE,METHOD,FIELD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE,ANNOTATION_TYPE,PACKAGE})
3.
反射结合
java.lang.reflect.AccessibleObject
public Boolean isAnnotationPresent(Class<?Extends Annotation> annotationClass) // 判断是否使用了指定的annotation
public Annotation[] getAnnotation() // 得到全部annotation
下面是实例代码
/**
2016年8月2日 下午3:34:14
yesiming
*/
package org.smi.o6;
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.METHOD)
public @interface Author {
String name() default "Hello";
String group() default "World";
}
/**
2016年8月2日 下午3:32:49
yesiming
*/
package org.smi.o6;
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)
public @interface Description {
String value();
}
/**
2016年8月2日 下午4:06:49
yesiming
*/
package org.smi.o6;
@Description("这是一个测试用的类")
public class AnnotationTest {
@Author(name="simon", group="smiGroup")
public void test() {
System.out.println("test over");
}
}
/**
2016年8月2日 下午3:34:48
yesiming
*/
package org.smi.o6;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> clssType = Class.forName("org.smi.o6.AnnotationTest");
if(clssType.isAnnotationPresent(Description.class)) {
System.out.println("实现了Description注解");
Description des = clssType.getAnnotation(Description.class);
System.out.println("des's value is: " + des.value());
}
Method[] methods = clssType.getDeclaredMethods();
for(Method me : methods) {
if(me.isAnnotationPresent(Author.class)) {
Author au = (Author)me.getAnnotation(Author.class);
System.out.println("author's name is: " + au.name());
System.out.println("author's group is: " + au.group());
}
}
}
}