一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

[J2SE 5.0专题][2.7]注解

时间:2008-01-12 编辑:简简单单 来源:一聚教程网

注解(Annotations)在我看来是J2SE 5.0中比较重大的新特性。将来的EJB 3.0规范将会全面利用该特性来简化Session Bean、 Message-Driven Bean和EntityBean的定义和实现。
Java的注解或多或少也是受了.NET的影响。这不是说Java本来没有注解,以前的诸如JavaDoc的标注,尤其@deprecated,都是注解,只不过这一次的更新将注解推到了Java历史上前所未有的高度。通过注解,我们可以实现原先相对复杂的高级功能。
先看一个实际的例子:
/*
* Created on 2004-12-28
*
*/
import java.lang.annotation.*;
/**
* @author Sean
*
*/
public class MyAnnotations {
@MyAnnotationForMethods (
index = 1,
info = "This is a method to test MyAnnotation.",
developer = "Somebody else"
)
public void testMethod1() {
// ...
}
@MyEmptyAnnotation
@MySingleElementAnnotation("For instruction purpose only.")
@MyAnnotationForMethods (
index = 2,
info = "This method is to show multiple annotations."
)
public void testMethod2() {
// ...
}

}
@Target(ElementType.METHOD)
@interface MyAnnotationForMethods {
int index();
String info();
String developer() default "Sean GAO";
}
@interface MyEmptyAnnotation {
}
@interface MySingleElementAnnotation {
String value();
}
在这个例子中,我先后定义了三个注解:第一个MyAnnotationForMethods包含三个成员,分别是index、info和developer,其中developer有默认值"Sean GAO",前面的@Target(ElementType.METHOD)是对这个注解的注解,说明该注解只能用于方法;第二个MyEmptyAnnotation是一个空的注解,可以作为标记使用,如早先的Serializable接口;第三个MySingleElementAnnotation包含一个成员,value,这个是硬性规定,当只有一个元素时,必须用value这个名称,它的类型可以是值型、String、Class、enum、或者上述数据类型的一元数组。

热门栏目