自定义注解的一个Demo
表名注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {
String name() default "";
}
字段约束
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Constraints {
boolean primaryKey() default false;
boolean allowNull() default true;
boolean unique() default false;
}
字段类型
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLInteger {
String name() default "";
Constraints constraints() default @Constraints;
}
字段类型
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLString {
int value() default 0;
String name() default "";
Constraints constraints() default @Constraints;
}
自定义注解的使用
@DBTable(name = "member")
public class Member {
@SQLString(30)
String firstName;
@SQLString(50)
String lastName;
@SQLInteger
Integer age;
@SQLString(value = 30, constraints = @Constraints(primaryKey = true))
String handle;
static int memberCount;
@Override
public String toString() {
return handle;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Integer getAge() {
return age;
}
public String getHandle() {
return handle;
}
}
解析注解
public class AnnotationMain {
public static void main(String[] args) throws Exception {
// 获取类的字节码文件对象
// 获取类的字节码文件对象
Class<?> aClass = Class.forName("top.lconcise.annotationdemo2.Member");
// 获取表名
DBTable dbTable = aClass.getAnnotation(DBTable.class);
String tableName = dbTable.name();
List<String> columnDefs = new ArrayList<>();
// 获取所有成员变量
Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
// 获取所有成员变量的注解
Arrays.stream(field.getDeclaredAnnotations()).forEach(annotation -> {
String columnName;
if (annotation instanceof SQLInteger) {
SQLInteger sInt = (SQLInteger) annotation;
if (sInt.name().length() < 1) {
columnName = field.getName().toUpperCase();
} else {
columnName = sInt.name();
}
columnDefs.add(columnName + " INT" + getConstraints(sInt.constraints()));
}
if (annotation instanceof SQLString) {
SQLString sString = (SQLString) annotation;
if (sString.name().length() < 1) {
columnName = field.getName().toUpperCase();
} else {
columnName = sString.name();
}
columnDefs.add(columnName + " VARCHAR(" + sString.value() + ")" + getConstraints(sString.constraints()));
}
});
});
StringBuilder createComand = new StringBuilder("CREATE TABLE " + tableName + "(");
columnDefs.forEach(columDef ->
createComand.append("\n " + columDef + ",")
);
String tableCreate = createComand.substring(0, createComand.length() - 1) + ");";
System.out.println("Tabled Creation SQL for " + tableName + " is :\n " + tableCreate);
}
public static String getConstraints(Constraints con) {
String constraints = "";
if (!con.allowNull()) {
constraints += " NOT NULL";
}
if (con.primaryKey()) {
constraints += " PRIMARY KEY";
}
if (con.unique()) {
constraints += " UNIQUE";
}
return constraints;
}
}
输出

网友评论