浅谈JAVA注解(Annotation)

一、废话

上一次写的简书,现在看,很尴尬(ㅎ.ㅎ)我很想删掉,但是毕竟第一次还是不删了吧。今天想学习一下Java中的注解,就当记录一下(顺便学习使用一下Markdown)。

二、发现与认识

public class IncomeFragment extends BaseFragment {    
@Bind(R.id.iv_user_img)    
ImageView mIvUserImg;    
@Bind(R.id.tv_income_user_name)   
TextView  mTvIncomeUserName;    
@Bind(R.id.tv_total_income)    
TextView  mTvTotalIncome;    
@Bind(R.id.tv_record)    
TextView  mTvRecord;    
@Bind(R.id.tv_bank_count)    
TextView  mTvBankCount;    
@Override    
protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        
View rootView = inflater.inflate(R.layout.fragment_income, container, false);
  • 代码上@Override(重写方法的注解),其实这是JDK1.5以后引入的新特性
    JDK1.5之后内部提供的三个注解
    @Deprecated 意思是“废弃的,过时的
    @Override 意思是“重写、覆盖
    @SuppressWarnings 意思是“压缩警告
  • 用着Butterknife开发的安卓童鞋肯定知道一键初始化控件带来方便
    看一下@Bind的源码
/*****
 *****Bind a field to the view for the specified ID. The view will automatically be cast to the field
 *****type.
 *****{@literal @}Bind(R.id.title) TextView title;
 *****/
@Retention(CLASS) 
@Target(FIELD)
public @interface Bind {
  /** View ID to which the field will be bound. */
  int[] value();
}

从源码上看注解类似于接口(其实就是一种特殊接口)

注解(Annotation)相当于一种标记,javac编译器、开发工具和其他程序可以通过反射机制来了解你的类及各种属性和方法上有无某个标记,就去干相应的事,标记可以加在包、类,属性、方法,方法的参数以及局部变量上。

三、了解与使用

认识注解前先认识元注解,元注解:在注解类上使用另一个注解类,那么被使用的注解类就称为元注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/*****
 *****创建者:  LeeBoo
 *****创建时间:2016/12/29 10:44 
 *****描述:    自定义注解 Annotation 
 *****/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Annotation {
}

上面代码的Retention和Target称为元注解

  • @Retention(RetentionPolicy.RUNTIME)
    Retention注解决定Annotation注解的生命周期
  • @Target({ElementType.METHOD, ElementType.TYPE})
    Target注解决定Annotation注解可以加在类身上,或者属性身上,或者方法等成分身上

Retention元注解有3种value属性值
@Retention(RetentionPolicy.SOURCE)
Annotation注解生命周期:只在java源文件中存在,javac编译成.class文件后注解就不存在了
@Retention(RetentionPolicy.CLASS)
Annotation注解生命周期:在java源文件(.java文件)中存在,编译成.class文件后注解也还存在,被Annotation注解类标识的类被类加载器加载到内存中后Annotation注解就不存在了
@Retention(RetentionPolicy.RUNTIME)
Annotation注解生命周期:让Annotation这个注解的生命周期一直程序运行时都存在

@Target元注解决定了一个注解可以标识到哪里,如标识在类上,在属性上,或者在方法上and so on, @Target默认值为可标识在任何地方

此时不是该看看@Deprecated、@Override、@SuppressWarnings这三个注解的@Retention和@Target注解的属性值分别是什么吗???

3.1为注解增加属性

@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.TYPE })
public @interface Annotation {
    boolean isProgrammer ();//添加属性
    **注解的属性定义方式就和接口中定义方法的方式一样**
}
3.1.1为注解增加属性的默认值
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.TYPE })
public @interface Annotation {
    boolean isProgrammer() default true;//添加属性默认值true
}
3.1.2注解中有一个名称为value的属性
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.TYPE })
public @interface Annotation {
    boolean isProgrammer() default true;//添加属性默认值true
    String value() default "Java Programmer"; //名称为value的属性 默认值为"Java Programmer"
}

3.2使用注解属性

//应用Annotation注解的isProgrammer属性为true
写法1
@Annotation(isProgrammer = true)
写法2
@Annotation
//应用Annotation注解的value属性为Java Programmer
写法1
@Annotation(value = "Java Programmer")   
写法2
@Annotation("Java Programmer")      **即value=可以省略**
public class AnnotationUse {
}

3.3注解高级属性

3.3.1、数组类型的属性

注解类添加数组类型的属性:int[] id() default {1,2,3};
使用类使用数组类型的属性:@Annotation(id={2,3,4})
如果数组属性只有一个值,这时候属性值部分可以省略大括号,如:@Annotation(id=2),表示数组属性只有一个值,值为2(如同Butterknife中onClick注解)

3.3.2、枚举类型的属性

注解类添加枚举类型的属性:Language language() default Language.OC;
使用类使用枚举类型的属性:@Annotation(language=Language.JAVA)

3.3.3、元注解类型的属性
a、元注解类型的属性创建
public @interface GradeAnnotation {
    String grade()  default  "高级开发程序员";//元注解GradeAnnotation设置有一个属性grade
}
b、元注解类型的属性添加
  • Language 枚举
public enum Language { 
   OC,       //object-C 
   JAVA      //java
 }
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Annotation {
    //添加一个int类型数组的属性
    int[] id() default {1,2,4};
    //添加一个枚举类型的属性,并指定枚举属性的缺省值,缺省值只能从枚举类Language 中定义的枚举对象中取出任意一个作为缺省值
    Language language() default Language.OC;
    //**为注解添加一个注解类型的属性,并指定注解属性的缺省值**
    GradeAnnotation gradeAnnotation () default @GradeAnnotation(grade = "初级开发程序员");
}
c、元注解类型的属性使用
@Annotation( id = {8,0,8}, language = Language.JAVA, gradeAnnotation = @GradeAnnotation (grade = "中级开发程序员"))
public class AnnotationUse {
  @Annotation  //将Annotation注解标注到main方法上
  public static void main(String[] args) {
   **使用反射机制对Annotation类的检查**
   一旦在某个类上使用了@Annotation,那么这个Annotation类的实例对象annotation就会被创建出来了
            Annotation annotation = (Annotation) AnnotationTest.class.getAnnotation(Annotation.class);
            System.out.println(annotation.language());//JAVA
            System.out.println(annotation.id().length);//3       
            GradeAnnotation ga = annotation.gradeAnnotation();
            System.out.println(ga.grade());//输出的结果为:"中级开发程序员"
   }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容