黑马程序员——注解

---------------------- android培训java培训、期待与您交流! ----------------------

注解

@SuppressWarnings("deprecation")//取消警告注解:告诉编译器,过时的也不用提示。

@deprecation//过时警告注解:不鼓励程序员使用这样的元素,通常是因为它很危险或存在更好的选择。

@override//覆盖注解:指重写父类里的方法,如否,编译器会发出警告。

例:

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})//指示要保留的种类
//Target是枚举类型的,METHOD指的是注解在方法上,而TYPE是注解在类上
public @interface AnnotationInter {
 //public String someThing();
}

 

//应用了注解类的类

@AnnotationInter//注解加在类上和方法上都不报错,这就是Target的功劳

public class AnnotationTest {

 //用main方法进行反射,虽然main方法在此类里,但那是迫不得已,并不属于此类。

@AnnotationInter

 public static void main(String[] args) {
  //检查此类是否应用了注解类
  //要对一个类进行检查,也叫做反射,反射首先要有字节码,所有的信息都在字节码里。
  if(AnnotationTest.class.isAnnotationPresent(AnnotationInter.class)){
   //字节码代表内存的二进制
   AnnotationInter ai = AnnotationTest.class.getAnnotation(AnnotationInter.class);   
   System.out.println(ai);//调用的是哪个注解
  }
  
 }

}

为注解增加基本属性

例1:

public @interface AnnotationInter {
 String color();//表示注解的方法
}

@AnnotationInter(color="red")//设置注解的属性

例2:

String color() default "blue";//缺省属性
String value();

@AnnotationInter("bbb")//只有一个属性时,不用写方法名。
System.out.println(ai.value());//输出注解里的属性值

例3:

public @interface AnnotationInter {
 String color() default "blue";
 String value();
 String[] arr() default {"111","222","333"};
}

@AnnotationInter(color="red",value="aaa",arr="444")//设置注解的属性
System.out.println(ai.value());//输出注解里的属性值
System.out.println(ai.color());//输出注解里的属性值
System.out.println(ai.arr().length);//输出注解里的属性值

为注解增加高级属性

枚举类型的属性

例:

public enum EnumTest {
RED,YELLOW,GREEN;
}

EnumTest lamp() default EnumTest.RED; //设置注解方法,并赋默认值

@AnnotationInter(color="red",value="aaa",arr="444",lamp=EnumTest.YELLOW)//设置注解的属性
System.out.println(ai.lamp());//输出注解里的属性值

注解类型的属性

例:

public @interface MetaAnnotation {//定义一个新的注解
 String value();
}

MetaAnnotation metaAnno() default @MetaAnnotation("nsy");//给注解赋值作为注解属性的缺省值

@AnnotationInter(color="red",value="aaa",arr="444",lamp=EnumTest.YELLOW,metaAnno=@MetaAnnotation("nbg"))
//设置注解的属性值
System.out.println(ai.metaAnno().value());//输出注解里的属性值

字节码类型的属性

例:

Class clazz() default String.class;//返回字节码类型

@AnnotationInter(color="red",value="aaa",arr="444",lamp=EnumTest.YELLOW,
metaAnno=@MetaAnnotation("nbg"),clazz=Double.class)//设置注解的属性

System.out.println(ai.clazz().getName());//输出注解里的属性值

 

---------------------- android培训java培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net/heima

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值