Thinking in Java:第二十章-注解

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));
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
《Thinking in Java》是由Bruce Eckel撰写的一本Java编程的经典教材,该书以英文语言出版。以下是该书的目录大纲: Chapter 1: Introduction to Objects - Introduction - The progress of abstraction - How objects communicate - Every object has an interface - The process of object-oriented design - Implementation hiding - Inheritance and reuse - Polymorphism and dynamic binding - Summary of object-oriented principles Chapter 2: Everything Is an Object - Primitive types - How the objects are created - Aliasing: All arguments are passed by value - Documentation comments - Controlling access to members of a class - First exposure to Java syntax Chapter 3: Operators - Thinking recursively - Operator precedence - Assignment with objects - Mathematical operators and precedence - Autoboxing and unboxing - Increment and decrement - Java logic operators - Bitwise operators - The instanceof operator - Summary of operators Chapter 4: Control Structures: Part 1 - True and false - The if-else statement - The switch statement - The while statement - The do-while statement - The for statement - Summary of control structures Chapter 5: Control Structures: Part 2 - The break and continue keywords - Foreach and multidimensional arrays - Using the comma operator - The return keyword - Summary of control structures Chapter 6: Initialization & Cleanup - Member initialization - Constructor initialization - Method overloading & generic methods - Order of initialization - Constructor & parameter lists - Garbage collection - The finalize() method - Summary of initialization and cleanup ......(接下去的章节继续)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值