注解的应用
代码示例:
package com.itheima.day2;
@IthimaAnnotation
public class AnnotationTest {
// 通过System.runFinalizersOnExit(true);的编译警告引出@SuppressWarnings("deprecation")
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
System.runFinalizersOnExit(true);
}
}
注解是Java1.5的新特性。
一个注解就是一个类,使用注解,就相当于创建了一个对象。
注解就相当于一个你的源程序中要调用的一个类,要在源程序中应用某个注解,得先准备好了这个注解类。就像你要调用某个类,得先有开发好这个类。
代码体现:
package com.itheima.day2;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//在注解类身上加的注解-->元注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface IthimaAnnotation {
}
package com.itheima.day2;
@IthimaAnnotation
public class AnnotationTest {
// 通过System.runFinalizersOnExit(true);的编译警告引出@SuppressWarnings("deprecation")
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
System.runFinalizersOnExit(true);
//利用反射检测@IthimaAnnotation注解类是否存在:
if(AnnotationTest.class.isAnnotationPresent(IthimaAnnotation.class)){
//得到一个注解的实列对象(通过反射)
IthimaAnnotation annotation =(IthimaAnnotation) AnnotationTest.class.getAnnotation(IthimaAnnotation.class);
//打印这个对象
System.out.println(annotation);
}
}
// 直接在刚才的类中增加一个方法,并加上@Deprecated标注,在另外一个类中调用这个方法。
@Deprecated
// 过时
public static void sayHello() {
System.out.println("hi,黑马程序员");
}
/*
* 总结:
*
* 注解相当于一种标记,在程序中加了注解就等于为程序打上了某种标记,
* 没加,则等于没有某种标记,以后,javac编译器,开发工具和其他程序可以用反射来了解你的类及各种元素上有无何种标记,
* 看你有什么标记,就去干相应的事。标记可以加在包,类,字段,方法,方法的参数以及局部变量上。
* 看java.lang包,可看到JDK中提供的最基本的annotation。
*/
}