package com.itcast.day2;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;//Retention默认为class阶段,注解MyAnnotation的生命周期为运行阶段@Retention(RetentionPolicy.RUNTIME)//默认值为任何元素,若在数组里只填写METHOD则使用注解的类编译报错@Target({ElementType.METHOD,ElementType.TYPE})public @interface MyAnnotation {}/** * Rentention * 关于java程序的三个阶段 * source阶段: .java--->编译--->.class * class阶段: .class-->进入jvm检查阶段--->字节码 * runtime阶段: 已经通过安全检查--被调入内存,被视为字节码 * */
package com.itcast.day2;@MyAnnotationpublic class MyAnnotationTest {}
package com.itcast.day2;public class MyAnnotationTestRun { public static void main(String[] args) { if(MyAnnotationTest.class.isAnnotationPResent(MyAnnotation.class)){ MyAnnotation MyAnnotation=MyAnnotationTest.class.getAnnotation(MyAnnotation.class); System.out.println(MyAnnotation);//com.itcast.day2.MyAnnotation() } }}
RententionPolicy.SOURCE、RententionPolicy.CLASS、RententionPolicy.RUNTIME;
分别对应java源代码—>class文件—>内存中的字节码
@Override ,用于给编译器看,是否符合重写规范(方法名,参数列表,返回值必须相同)。一般是自己写的代码.------SOURCE阶段
@SuppressWarnings 用于告诉编译器,不要在编译阶段发出警告。一般是自己写的代码.---SOURCE阶段
@Deprecated 用于标注方法是否过时。一定是在调入内存后,运行期扫描二进制。有可能是别人写的我在调用。---RUNTIME阶段
新闻热点
疑难解答