JAVA元数据注释初探
来源:优易学  2011-9-24 19:56:28   【优易学:中国教育考试门户网】   资料下载   IT书店

  JAVA的元数据功能是JDK1.5才开始支持的,以前都没有,正因为是新支持的,所以有关于它的介绍挺少,用处也不太多,最近发现很多框架都可以把它用来配置一些东西,以代替以前比较复杂的XML配置。想像一下,在JAVA代码中直接写入注释来配置,那该是多么好的事情,让我们写习惯了代码和看习惯了代码的人来说,这无疑是一件很爽的事情。
  我们可以使用JAVA内置的注释内型,如果觉得不够用,可以定义自己的注释内型,定义如下
  /*
  * MyType.java
  *
  * Created on 2006年12月7日, 下午3:40
  *
  * To change this template, choose Tools   Template Manager
  * and open the template in the editor.
  */
  package testAnno;
  /**
  *
  * @author lbf
  */
  import java.lang.annotation.*;
  @Retention(RetentionPolicy.RUNTIME)
  @Target()
  public @interface MyType {
  String authorName();
  String lastModified();
  String bugFixes() default "ok";
  }
  这里我定义了一个我自己的注释类,声明方式和声明接口差不多,只不过在interface前面多了一个@符号.
  注释类也可以用注释类注释,如此下去.
  @Retention(RetentionPolicy.RUNTIME)
  这句表示它的保存范围是到RUNTIME,也就是运行时,这样在类运行的时候,我们也可以取到有关它的信息.
  @Target()
  这句表示它的适用对象,它可以用在哪里地方,我这里定义的是它可以用在类的定义和方法的定义上
  然后我们看我们是怎么为我们写的类加上注释的
  /*
  * Test1.java
  *
  * Created on 2006年12月7日, 下午3:34
  *
  * To change this template, choose Tools   Template Manager
  * and open the template in the editor.
  */
  package testAnno;
  /**
  *
  * @author lbf
  */
  import java.lang.annotation.*;
  @MyType(authorName="hadeslee",lastModified="20061207")
  public class Test1 {
  /** Creates a new instance of Test1 */
  public Test1() {
  }
  @Deprecated
  @MyType(authorName="hadeslee",lastModified="20061207",bugFixes="what")

[1] [2] 下一页

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训