本文已参与「新人创作礼」活动,一 起开启掘金创作之路。
java自定义注解+反射(模拟mybatis)
Java5.0定义的元注解 @Target 作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
取值(ElementType)有:
- CONSTRUCTOR:用于描述构造器
- FIELD:用于描述域
- LOCAL_VARIABLE:用于描述局部变量
- METHOD:用于描述方法
- PACKAGE:用于描述包
- PARAMETER:用于描述参数
- TYPE:用于描述类、接口(包括注解类型) 或enum声明
@Retention 作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)
取值(RetentionPoicy)有:
- SOURCE:在源文件中有效(即源文件保留)
- CLASS:在class文件中有效(即class保留)
- RUNTIME:在运行时有效(即运行时保留)
@Documented 作用:用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
@Inherited @Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
测试示列
package com.test;
import java.lang.annotation.*;
import java.lang.reflect.Field;
/**
* @author TANGSHUAI
* @version 1.0
* @date 2021-12-21 10:44
* 练习放射操作注解,简易ORM
*/
public class Test2 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class aClass = Class.forName("com.test.Student");
//通过反射获得注解
Annotation[] annotations = aClass.getAnnotations();
for (Annotation annotation : annotations) {
//@com.test.TableName(value=db_student)
System.out.println(annotation);
}
//获得注解value值
TableName tableName = (TableName)aClass.getAnnotation(TableName.class);
//db_student
System.out.println(tableName.value());
//获取类指定的注解
Field f = aClass.getDeclaredField("name");
FieldName annotation = f.getAnnotation(FieldName.class);
//db_name
System.out.println(annotation.columnName());
//10
System.out.println(annotation.length());
//String
System.out.println(annotation.type());
}
}
@TableName("db_student")
class Student{
@FieldName(columnName = "db_id",type="int",length = 10)
private int id;
@FieldName(columnName = "db_age",type="int",length = 10)
private int age;
@FieldName(columnName = "db_name",type="String",length = 10)
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public Student() {
}
}
//自定义注解获取表名
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableName{
String value();
}
//属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldName{
String columnName();
String type();
int length();
}