您的位置:首页 > 编程语言 > Java开发

jdk 1.5新特性---注解

2011-01-19 16:14 190 查看
注解是程序向编译器传达某种编译信息的方式。比如对一些过时的方法,编译器在编译的时候会提醒程序员:此方法不推荐使用。但是程序员觉得看到这个提示很不爽,于是说:“哥玩了几十年的程序,这个都不知道吗?你不用给我提示了,我懂滴。”于是程序员在程序中嵌入一句

@SuppressWarnings("deprecated");这行代码表示关闭方法过时提示。于是编译器就乖乖的不提示了。这就是注解!

注解的语法,除了@符号的使用以外,它基本上与java的固有语法一致,java内置了三种

注解,定义在java.lang包中。

@Override 表示当前方法是覆盖父类的方法。使用这个注解,是告诉编译器,这里必须是覆盖父类的方法。如果你发现不是覆盖父类方法的,请打断它的腿!

@Deprecated 表示当前元素是不赞成使用的。若在程序中使用了这个注解,编译会提示这个方法过时,但可以运行。

@SuppressWarnings 叫压缩警告,表示关掉编译器的某些警告。告诉编译器,你少罗嗦,照编译就可以了!

下面自定义一个注解,并使用它:

编写注解类:MyAnnotation.java

package blh.review.reflect;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/* @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括:
*         RetentionPolicy.SOURCE 注解将被编译器丢弃
*         RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃
*         RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。
* */
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
public String anotDsc() default "Myannotation";
}


编写使用注解的类,并检查该类是否使用了注解,打印出注解的信息。

package blh.review.reflect;
import java.lang.reflect.Method;

@MyAnnotation
public class AnnotationTest {
@MyAnnotation(anotDsc="This is an Annotation test 0!")
public void test0(){}
@MyAnnotation(anotDsc="This is an Annotation test 1!")
public void test1(){}
@MyAnnotation(anotDsc="This is an Annotation test 2!")
public void test2(){}
public static void main(String[] args) {
//Use reflect return method
Method [] annMethods= AnnotationTest.class.getMethods();
for(Method annMethod:annMethods){
if (annMethod.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = annMethod.getAnnotation(MyAnnotation.class);
System.out.println("MyAnnotation( method = " + annMethod.getName()
+  " , anotDsc = "
+ annotation.anotDsc() + " )");
}
}
}
}


打印结果:

MyAnnotation( method = test0 , anotDsc = This is an Annotation test 0! )

MyAnnotation( method = test1 , anotDsc = This is an Annotation test 1! )

MyAnnotation( method = test2 , anotDsc = This is an Annotation test 2! )

参考资料:

http://www.javaeye.com/topic/400085
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: