java中的注解

1)自定义注解:

	1)定义注解:
		语法:public @interface 注解名{}
		举例:
			public @interface MyAnnotation{
				String name() default "jack";
			}
	
	2)定义注解的属性:
		语法:
			类型 属性名();
			类型 属性名() default 默认值;
		
		赋值:
			说明:在使用时,进行赋值。
			举例:@MyAnnotation(name="hello")
		
		特殊属性value:

			类型 value();
				只给value设值:	@MyAnnotation(value="hello") 或 @MyAnnotation("hello")
				给多个属性设值:@MyAnnotation(value="hello",name="aaa")
			
			类型[] value();
				只给value设值:	@MyAnnotation(value={"a","b"}) 或 @MyAnnotation({"a","b"}) 或 @MyAnnotation({"a"}) 或 @MyAnnotation("a")			
				给多个属性设值:同上。

		注意:注解的属性的类型只能是:基本类型、String、Class、枚举、注解类型 和 这些类型的一维数组。


											
2)元注解:

	1)概念:加在注解上的注解。
	
	2)常用的元注解:
		@Retention:注解的保留范围
			RetentionPolicy.SOURCE:	注解存在于源文件中
			RetentionPolicy.CLASS:		注解存在于字节码文件中
			RetentionPolicy.RUNTIME:	注解存在于运行时
			
		@Target:注解出现的位置
			eg:@Target(ElementType.METHOD)
				@Target({ElementType.FIELD,ElementType.METHOD})
				
		@Inherited:  被该元注解修饰的Annotation类将具有继承性,如果某个类使用了被@Inherited修饰的Annotation, 则该类的子类会自动加上这个被@Inherited修饰的Annotation。
	
		@Documented: 被该元注解修饰的Annotation类将被javadoc工具提取成文档。
	
	

3)注解处理器相关API:

	1)java.lang.annotation.Annotation:
		说明:该接口是所有注解类的父接口。

	2)java.lang.reflect.AnnotatedElement:	
		概念:表示一个正在VM中运行并且被注解修饰的元素(类、方法、字段等),该接口允许通过反射的方式来读取元素上的注解。
		
		实现类:java.lang.reflect包下的:Class、Constructor、Method、Field、Package
		
		说明:该接口中的方法返回的所有注解都是不可变的。

		该接口中的方法:
			1>getAnnotation(clazz)
				<T extends Annotation> T getAnnotation(Class<T> annotationClass):
				说明:如果该元素被指定类型的注解所修饰,则返回该注解,否则返回null。

			2>getAnnotations()	
				Annotation[] getAnnotations()
				说明:返回此元素上所有的注解。
	
			3>getDeclaredAnnotations()	
				Annotation[] getDeclaredAnnotations()
				说明:返回直接在该元素上修饰的所有的注解,该方法会忽略掉从父类继承过来的注解。
			
			4>isAnnotationPresent(clazz)
				boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
				说明:判断该元素是否被指定类型的注解修饰。

				
				
				
				
				

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值