黑马程序员---------Java面向对象——注解

来源:互联网 发布:mac卸载qq输入法 编辑:程序博客网 时间:2024/05/16 12:08
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ---  

注解的应用
代码示例:
package com.itheima.day2;@IthimaAnnotationpublic 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;@IthimaAnnotationpublic 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。 */}
                                             
0 0
原创粉丝点击