1、申明一个注解类、用到关键字interface 前面加个@
public @interface myAnnotation
2、添加成员、可以看成接口的方法。类型 成员名称+();
String name();
String value();
3、使用 Target 元注释、避免他人误用您的注释类型、 应用于类型、方法、构造函数和其他注释类型
@Target({
ElementType.TYPE,
ElementType.METHOD,
ElementType.CONSTRUCTOR,
ElementType.ANNOTATION_TYPE
})
4、使用 Retention 元注释
4、1 RUNTIME 编译后在class文件中程序可以读到
4、2 SOURCE 不在编译的class文件中程序不能读到
5、Documented
Documented 表示注释应该出现在类的 Javadoc 中。
6、使用 Inherited 元注释
添加 @Inherited 后,您将看到 InProgress 出现在注释类的子类中
demo
myAnnotation.class
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface myAnnotation{
String name();
String value();
}
使用
@myAnnotation(name="table",value="12313")
class User extends Person{
}
main
public static void main(String[] args) throws Exception {
Annotation[] anns=User.class.getAnnotations();
int i=0;
int len=anns.length;
for(i=0;i<len;i++){
System.out.println(anns[i]);
}
}
结果:
@test.myAnnotation(name=table, value=12313)
注解应用:
1、 JPA javax.persistence
2、 spring 注入注解
等等。。。
http://blog.sina.com.cn/s/blog_61f4999d0100l26e.html java注解应用
http://blog.youkuaiyun.com/hbzyaxiu520/archive/2011/02/28/6212969.aspx JAVA自定义注释(Target,Retention,Documented,Inherit)