黑马程序员-注解

------- android培训java培训、期待与您交流! ----------
java1.5新特性中的注解:相当于一个标记,javac编译器,开发工具和其他程序可以用反射来
了解是否有某种标记,从而做相应的操作。
@SuppressWarnings:警告
@Deprecated:过时
@Override:重写

元注解:注解类上加持的注解称为元注解,一般是用来设置该注解类的运行时间以及作用范围。
常见的有@Retention @Target
@Retention的属性值:枚举类RetentionPolicy的枚举常量(RetentionPolicy.RUNTIME  RetentionPolicy.CLASS RetentionPolicy.SOURCE)
@Target的属性值:枚举类ElementType的枚举常量(TYPE,METHOD,CONSTRUCTOR,FIELD...)

自定义注解:
1.定义一个最简单的注解
2.把它加在某个类上
3.用反射进行测试类的定义上是否有注解
@Retention(RetentionPolicy.RUNTIME)//元注解
@Target({ElementType.METHOD,ElementType.TYPE})
@interface MyAnnotation
{}


@MyAnnotation
class AnnotationTest
{
	public static void main(String[] args)
	{
		if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class))
		{
			MyAnnotation annotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);
			System.out.println(annotation);
		}
	}
}

注解类的内部可以定义不同类型的变量,通过注解时设置不同的变量值,然后通过反射可以获取这些变量的值。
注解可以定义的变量类型有:8个基本数据类型 数组 String  Enum  Class  Annotation

一个简答的反射取得注解变量值的例子:
注解类MetaAnnotation:
public @interface MetaAnnotation {
	String value() default "zhangsan";
}
注解类MyAnnotation
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.TYPE,ElementType.METHOD})
public @interface MyAnnotation {
	String  value() default "abc" ;
	String color() default "red";
	int[] arrInt() ;
	TrafficLamp lamp() default TrafficLamp.RED;
	Class clazz() default String.class;
	MetaAnnotation metaAnnotation() default @MetaAnnotation("lisi");
}

注解测试类AnnotationTest:
import java.lang.reflect.Method;

@MyAnnotation(color="blue",arrInt=1,clazz=Integer.class,metaAnnotation=@MetaAnnotation("wangwu"))
public class AnnotationTest {

	@MyAnnotation(value="xyz",arrInt=2,lamp=TrafficLamp.YELLOW)
	public static void main(String[] args)throws Exception {
		// TODO Auto-generated method stub
		if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){
			MyAnnotation annotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);
			System.out.println(annotation);
		}
		Method method = AnnotationTest.class.getMethod("main", String[].class);
		if(method.isAnnotationPresent(MyAnnotation.class)){
			MyAnnotation methodAnnotation =method.getAnnotation(MyAnnotation.class);
			System.out.println(methodAnnotation);
		}
	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值