1:注解(也被成为元数据),为我们在代码中添加信息提供了一种形式化的方法,使我们可以在稍后的某个时刻方便的使用这些数据。Java SE5中预先定义了一些元数据,但一般来说,主要还是需要程序员自己添加新的注解,并按照自己的方式使用它们。
2:@Target:定义你的注解将用于什么地方(例如一个方法或者一个域),@Retention:用来定义你的注解在哪一级可以使用,在源代码中(SOURCE),类文件中(CLASS),或者运行时(RUNNING):没有元素的注解(也被称为标记注解):Test:
3:简单的注解:UseCase
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
public int id();
public String description() default "no description";
}
public class PasswordUtils {
@UseCase(id = 47, description = "Password must contain at least one numeric")
public boolean validatePassword(String password) {
return (password.matches("\\w*\\d\\w*"));
}
@UseCase(id = 48, description = "")
public String encrypePassword(String password) {
return new StringBuilder(password).reverse().toString();
}
}
public class UseCaseTracker {
public static void trackUseCases(List<Integer> used, Class<?> cl) {
for (Method m : cl.getDeclaredMethods()) {
// 获取这个方法上的注解
UseCase annotation = m.getAnnotation(UseCase.class);
if (annotation != null) {
System.out.println(annotation.id() + " : " + annotation.description());
}
used.remove(new Integer(annotation.id()));
}
}
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<Integer>();
Collections.addAll(integerList, 47,48,49);
trackUseCases(integerList, PasswordUtils.class);
System.out.println(integerList);
}
}
4:生成外部文件:一个幼稚的根据Java bean 生成sql语句的实例:TableCreator
@Target(ElementType.TYPE) // applies to classes only
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {
public 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 constranints() default @Constraints;
}
@DBTable(name = "MEMBER")
public class Member {
@SqlString(30)
String name;
@SqlInteger
int age;
@SqlString(value = 30, constranints = @Constraints(primaryKey = true))
String handle;
@Override
public String toString() {
return handle;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getHandle() {
return handle;
}
public void setHandle(String handle) {
this.handle = handle;
}
}
/**
* Created By Percy Gauguin On 2018/2/4
* 读取一个类文件,检查其上的数据库注解,并生成用来新建数据库的sql命令
*/
public class TableCreator {
public List<String> create(String[] args) throws ClassNotFoundException {
if (args.length < 1) {
System.out.println("arguments: annotated classes");
System.exit(0);
}
List<String> sqls = new ArrayList<String>();
for (String className : args) {
Class<?> cl = Class.forName(className);
DBTable db = cl.getAnnotation(DBTable.class);
if (db == null) {
System.out.println("No DBTable annotation in class " + className);
continue;
}
String tableName = db.name().toLowerCase();
List<String> columns = new ArrayList<String>();
for (Field field : cl.getDeclaredFields()) {
String columnName = null;
Annotation[] annotations = field.getDeclaredAnnotations();
if (annotations.length < 1) {
continue;
}
if (annotations[0] instanceof SqlInteger) {
SqlInteger sInt = (SqlInteger) annotations[0];
if (sInt.name().length() < 1) {
columnName = field.getName().toLowerCase();
}
else {
columnName = sInt.name();
}
columns.add(columnName + " int" + getConstraints(sInt.constraints()));
}
if (annotations[0] instanceof SqlString) {
SqlString sqlString = (SqlString) annotations[0];
if (sqlString.name().length() < 1) {
columnName = field.getName().toLowerCase();
}
else {
columnName = sqlString.name();
}
columns.add(columnName + " varchar(" + sqlString.value() + ")" + getConstraints(sqlString.constranints()));
}
}
StringBuffer sb = new StringBuffer("create table ");
sb.append(tableName).append(" (");
for (String column : columns) {
sb.append("\n" + column + ",");
}
sb.deleteCharAt(sb.length()-1);
sb.append(")");
sqls.add(sb.toString());
}
return sqls;
}
private 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;
}
public static void main(String[] args) throws ClassNotFoundException {
TableCreator tc = new TableCreator();
String[] str = new String[]{"think_in_java.twenty.sql.Member"};
System.out.println(tc.create(str));
}
}