1.内置注解:
@Override:重写方法
@Deprecated:标注过期
@SuppressWarnings("all"):消除所有警告。
2.元注解:
@Target:
-作用: 用来描述注解的使用范围(即:被描述的注解可以用在什么地方)
所修饰范围 | 取值ElementType |
package 包 | PACKAGE |
类、接口、枚举、Annotation类型 | TYPE |
类型成员(方法、构造方法、成员变量、枚举值) | CONSTRUCTOR:用于描述构造器 FIELD:用于描述域 METHOD:用于描述方法 |
方法参数和本地变量 | LOCAL_VARIABLE:用于描述局部变量 PARAMETER:用于描述参数 |
-@Target(value=ElementType.TYPE)
@Retention
-作用: 表示需要在什么级别保存该注释信息,用于描述注解的生命周期
取值 RetentionPolicy | 作用 |
SOURCE | 在源文件中有效(即源文件保留) |
CLASS | 在class文件中有效(即class保留) |
RUNTIME | 在运行时有效(即运行时保留) 为Runtime可以被反射机制读取 |
@Documented
Documented注解的作用是:描述在使用 javadoc 工具为类生成帮助文档时是否要保留其注解信息。
@Inherited
Inherited注解的作用是:使被它修饰的注解具有继承性(如果某个类使用了被@Inherited修饰的注解,则其子类将自动具有该注解)。
反射机制读取注解
/** * @Author panghl * @Date 2020/10/7 21:45 * @Version 1.0 * @Description 类上的注解 **/ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface SxtTable { String value(); }
/** * @Author panghl * @Date 2020/10/7 21:49 * @Version 1.0 * @Description 属性的注解 **/ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface SxtField { String columnName(); String type(); int length(); }
/** * @Author panghl * @Date 2020/10/7 21:46 * @Description TODO **/ @SxtTable("tb_student") public class SxtStudent { @SxtField(columnName = "id",type = "int",length = 10) private int id; @SxtField(columnName = "sname",type = "String",length = 10) private String studentName; @SxtField(columnName = "age",type = "int",length = 3) private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
/** * @Author panghl * @Date 2020/10/7 21:51 * @Description 使用反射读取注解的信息,模拟处理注解信息的流程 **/ public class Demo03 { public static void main(String[] args) { try { Class<?> clazz = Class.forName("com.bjsxt.test.annotation.SxtStudent"); //获取类的所有有效注解 Annotation[] annotations = clazz.getAnnotations(); for (Annotation a: annotations) { System.out.println(a); } //获得类指定的注解 SxtTable annotation = clazz.getAnnotation(SxtTable.class); System.out.println(annotation.value()); //获得类的属性的注解 Field f = clazz.getDeclaredField("studentName"); SxtField sxtField = f.getAnnotation(SxtField.class); System.out.println(sxtField.columnName()+":"+sxtField.length()+":"+sxtField.type()); //根据获得的表名、字段的信息,拼出DDL语句,然后使用JDBC执行这个SQL,在数据库中生成相关的表 } catch (Exception e) { e.printStackTrace(); } } }