来!认识一下强大的Annotation
1.annotation是什么?
2.我们身边的Annotation
? ? ? ?
?
3.写一个简单的annotation 感官认识一下,详细介绍请关注我博客的后期文章
4.因为Annotation的使用和反射息息相关,所以本例只是简单的介绍了一下annotation,如果本文受大家欢迎的话,会尽快出更详细的文章。
?
?
package com.cxy.annotation;import java.lang.annotation.Annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.util.Date;/** * @author cxy */public class AnnotationTest{@CxyAnnotation(title="名字",descript="记录用户姓名")public String name="";public static void main(String[] args) throws Exception{Date d=new Date();d.getYear(); //这个Date方法被划伤了横线 代买这个方法已经过时oldMethod(); //这个自定义的方法 被打上了过时方法的标记 @DeprecatedSystem.out.println("====================");Annotation[] aArray=AnnotationTest.class.getField("name").getAnnotations();//为了演示方便这里我知道肯定会有一个CxyAnnotation在数组的第一个 所以直接取,实际工作中请使用遍历去判断Annotation na=aArray[0]; System.out.println("成员变量name的扩展信息:");System.out.println("name代表:"+((CxyAnnotation)na).title());System.out.println("name具体描述:"+((CxyAnnotation)na).descript());}//检查父类是否有一个这样的方法让子类重写。@Overridepublic String toString(){return "AnnotationTest [getClass()=" + getClass() + ", hashCode()="+ hashCode() + ", toString()=" + super.toString() + "]";}//标记这个方法已经过时@Deprecatedpublic static void oldMethod(){System.out.println("这个方法已经过时了");}}//自己定义的一个Annotation@Retention(RetentionPolicy.RUNTIME) //保留注释到程序运行@Target(ElementType.FIELD) //这个annotation是标记在field上的@interface CxyAnnotation{String title();String descript();}?
?
?
声明:
1.原创文章,转载请标明并加本文连接。
2.文章反映个人愚见,如有异议欢迎讨论指正
?