首页 > 技术文章 > 注解和反射

jingjiu 2019-12-24 11:58 原文

typora-copy-images-to: zccmd_images
typora-root-url: zccmd_images

注解

内置注解

1、@Override

重写

2、@Deprecated

提示已过期

3、@SuppressWarnings("all")

镇压告警

元注解

//表示我们注解可以用在哪些地方
@Target(value = {ElementType.METHOD, ElementType.TYPE})
//runtime>class>sources,表示我们注解在什么阶段有效
@Retention(value = RetentionPolicy.RUNTIME)
//表示是否将注解生产在javaDoc中
@Documented
//子类可以继承父类的注解
@Inherited
@interface MyAnnotation {

}

1、@Target

表示我们注解可以用在哪些地方

2、@Retention

runtime>class>sources,表示我们注解在什么阶段有效

3、@Documented

表示是否将注解生产在javaDoc中

4、@Inherited

子类可以继承父类的注解

 

自定义注解

//表示我们注解可以用在哪些地方
@Target(value = {ElementType.METHOD, ElementType.TYPE})
//runtime>class>sources,表示我们注解在什么地方有效
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation {
 String name() default "";
 int age();
 int id() default -1;
 String[] schools() default {"西部开源", "清华大学"};
}

当只有一个参数时,推荐使用String value();

反射

1、通过反射获取类的Class对象

Class c1 = Class.forName("com.jingjiu.User");

image-20191224114851270

image-20191224114359103

 

推荐阅读