注解 Annotation
作用:
- 不是程序本身,可以对程序做出解释
- 可以被其他程序读取(编译器等)
格式:
- @注释名 使用方式 @Override
- 还可以添加参数值 @SuppressWarnings(value = “unchecked”)
使用位置:
- package
- class
- method
- field
内置注解:
- @Override
- 重写
- @Deprecated
- 修饰方法/属性/类,表示不推荐使用
- @SuppressWarnings
- 抑制编译时的警告信息
自定义注解:
使用 @interface 自定义注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Field {
String column();
String type();
int length() default 5;
}
元注解:
负责注解其他注解,Java定义了4个标准 meta-annotation 类型
- @Target
- 取枚举的值 ElementType
- PACKAGE:包
- TYPE:类/接口/枚举/Annotation类型
- CONSTRUCTOR:构造器
- FIELD:域
- METHOD:方法
- LOCAL_VARIABLE:局部变量
- PARAMETER:方法参数
- 取枚举的值 ElementType
- @Retention
- 取枚举值 RetentionPolicy
- SOURCE:在源文件中有效
- CLASS:在class文件中有效
- RUNTIME:在运行时有效,可以被反射机制读取,常用
- 取枚举值 RetentionPolicy
- @Documented
- @Inherited
注解信息读取:
/**
* 表注解
* */
@Target(value = {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String value();
}
/**
* 字段注解
* */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Field {
String column();
String type();
int length() default 5;
}
/**
* 注解使用
* */
@Table("t_student")
public class Student {
@Field(column = "id", type = "varchar2", length = 10)
private Integer id;
@Field(column = "nameeeee", type = "varchar2", length = 20)
private String name;
//getset
}
/**
* 读取注解信息
* */
@Test
public void test1() throws Exception {
Class<?> clazz = Class.forName("annotation.Student");
/* 获得类的所有有效注解 */
Annotation[] annotations = clazz.getAnnotations();
for (Annotation a : annotations) {
System.out.println(a); // - @annotation.Table(value=t_student)
}
/* 获得类的指定注解 */
Table table = clazz.getAnnotation(Table.class);
System.out.println(table.value()); // - t_student
/* 获得类的属性注解 */
Field name = clazz.getDeclaredField("name");
annotation.Field field = name.getAnnotation(annotation.Field.class);
System.out.println(field); // - @annotation.Field(length=20, column=nameeeee, type=varchar2)
}