// @Twizzle标注toggle()方法。 @Twizzlepublic void toggle() {
} // 声明Twizzle标注 public @ interface Twizzle { }标注可以包括一个关键字和值的对构成的列表:
//等同于 @Edible(value = true)@Edible(true)Item item = new Carrot(); public @interface Edible { boolean value() default false;} @Author(first = "Oompah", last = "Loompah")Book book = new Book(); public @interface Author { String first(); String last();}
标注声明中可以用标注说明使用方式、时间和对象:
@Retention (RetentionPolicy. RUNTIME ) // 该标注可以在运行时通过反射访问。 @Target ({ElementType. METHOD }) // 该标注只用于类内方法。 public @ interface Tweezable { }编译器保留一组标注用于特定语法目的 (包括 @Deprecated, @Override和@SuppressWarnings等)。
标注通常用于软件框架为用户定义的类和方法提供引用外部资源的情形,如XML配置文件、事务环境等。以下是一个标注过的EJB 3.0的类:
@ Entity // 声明实体类 @Table (name = "people" ) // 映射该类到 "people"表 class Person implements Serializable { @Id // 映射到主键 @GeneratedValue (strategy = GenerationType. AUTO ) // 数据库自动生成键值 private Integer id ; @Column (length = 32 ) // 限长32个字符 private String name ; public Integer getId () { return id ; } public void setId ( Integer id ) { this. id = id ; } public String getName () { return name ; } public void setName ( String name ) { this. name = name ; } }以上代码中标注不执行任何特定行为,而是为在运行时,EJB容器获得足够的信息,生成对象到关系数据库的映射。
相关资源:Java Annotation的讲解和例子