注解、反射相关(持续更新)

注解

1.元注解

元注解有:@Target,@Retention,@Documented,@Inherited 

@Target 表示该注解用于什么地方,以jdk 1.8为例子 ElemenetType 参数包括: 
@Target(ElementType.TYPE)——接口、类、枚举、注解

			@MyAnnotation 
			public interface/class/enum/@interface test {
			}

@Target(ElementType.FIELD)——字段、枚举的常量
			
			public class test {
					@MyAnnotation 
					private String userName;
			}
			
			public enum AppResponseStatus {
    		  		@MyAnnotation 
    				SUCCESS(0)
   			}
			
@Target(ElementType.METHOD)——方法

			@MyAnnotation 
			public void test(String name) {
			}
			
@Target(ElementType.PARAMETER)——方法参数 

			public void test(@MyAnnotation String name) {
			}
			
@Target(ElementType.CONSTRUCTOR) ——构造函数
			
			public void test(String name) {
				@MyAnnotation 
				public test(){
				}
			}
			
@Target(ElementType.LOCAL_VARIABLE)——局部变量
		
			public void test(String name) {
					@MyAnnotation 
					int a = 0;
			}

@Target(ElementType.ANNOTATION_TYPE)——注解
			
			@MyAnnotation 
			public @interface DataSource {
			}
			
@Target(ElementType.PACKAGE)——包
			
			@MyAnnotation 
			package com.basicclass.multithreading.singletonpattern;
			
@Target(ElementType.TYPE_PARAMETER)——泛型

			public class Generic<@MyAnnotation T> {
			}

@Target(ElementType.TYPE_USE)——表示该注解能使用在使用类型的任意语句中

			例如:
			 ArrayList<@MyAnnotation String> list = new ArrayList<>();

@Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括: 
	RetentionPolicy.SOURCE 注解将被编译器丢弃 
	RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃 
	RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。 
 
@Documented 将此注解包含在 javadoc 中 
 	生成的javaDoc 对应的index.html 会展示对应的注解
@Inherited 允许子类继承父类中的注解 

CSDN-TheMain183-@Inherited详解

反射

反射常用注解

1.isAnnotationPresent  A.isAnnotationPresent(B.class);意思就是:注释B是否在此A上。如果在则返回true;不在则返回false2.getAnnotations 只有当父类的注解中用@Inherited修饰,子类的getAnnotations()才能获取得到父亲的注解以及自身的注解

3.getDeclaredAnnotations() 只会获取自身的注解,无论如何都不会获取父亲的注解


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值