1.什么是java的注解?
注解可以理解为java中一些类、方法、或者字段的特殊标记,我们的自定义注解通常会结合反射等方法来方便获取某些我们自义的信息。
2.常见的java注解
- @Deprecated (标记一个方法过期)
- @Override (覆写)
- @SuppressWarnings (用来抑制编译器生成警告信息)
3.元注解(贴在注解上的注解)
1.@Target
2.@Retention
3.@Documented
4.@Inherited
@Target:说明了Annotation所修饰的对象范围,即是注解贴到哪个位置,封装在ElementType枚举类中。
取值(ElementType)有:
1.CONSTRUCTOR:用于描述构造器
2.FIELD:用于描述域
3.LOCAL_VARIABLE:用于描述局部变量
4.METHOD:用于描述方法
5.PACKAGE:用于描述包
6.PARAMETER:用于描述参数
7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
想知道多的可以看源代码,我就不说了,上图:
@Retention:定义了该Annotation被保留的时间长短,表示需要在什么级别保存该注释信息,用于描述注解的生命周期 (即:被描述的注解在什么范围内有效), 自定义的注解必须保存到运行时期。
取值(RetentionPolicy)有:
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在运行时有效(即运行时保留)
@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。就理解为继承吧,反正也用得比较少,不说也罢。
4.注解使用演示
4.1注解的定义
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Retention 注解保存的时期,RetentionPolicy枚举类中
* @Target 贴到哪个位置,封装在ElementType枚举类中 自定义的注解必须保存到运行时期
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.FIELD })
public @interface Permission {
String value();
}
4.2注解的引用
import java.util.Date;
import lombok.Data;
@Permission("顾客实体类")
@Data
public class Customer {
public static int CUSTOMER_SEX_MAN = 1;
@Permission("编号")
private Long id;
@Permission("名字")
private String name;
@Permission("日期")
private Date date;
@Permission("地址")
public int address;
}
4.3注解的获取测试(主要是反射获取)
import java.lang.reflect.Field;
public class AnnotationDemo {
public static void main(String[] args) throws Exception {
Class clazz = Customer.class;
System.out.println("全限制定类名为:" + clazz.getName());// 全限定类名的获取
System.out.println("简单类名为:" + clazz.getSimpleName());// 简单类名
Permission annotation = (Permission) clazz.getAnnotation(Permission.class);
System.out.println("Customer类上的注解值为:" + annotation.value());
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
// java中的修饰码 如public 1 private 2 protect 4 static 8
if (field.getModifiers() == 2) {
String annotaionValue = field.getAnnotation(Permission.class).value();
System.out.println("private字段" + field.getName() + "注解的值为:" + annotaionValue);
}
}
}
}
4.4测试输入结果:
全限制定类名为:MyAnnotation.Customer
简单类名为:Customer
Customer类上的注解值为:顾客实体类
private字段id注解的值为:编号
private字段name注解的值为:名字
private字段date注解的值为:日期
5.给注解设置默认值
注解示例:
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.CONSTRUCTOR, ElementType.METHOD })
public @interface UserAnnotaion {
String name() default "默认值"; //可以为注解设置默认值
int age() default 17;
}
使用方法:
public class AnnotationDemo {
@UserAnnotaion(name = "小羞羞",age = 17)
public void doWork() {
}
}