首页 > 代码库 > Java编程思想-注解生成外部例子代码

Java编程思想-注解生成外部例子代码

java注解属于java中高大上的功能,许多开源框架都使用了java注解的功能。比如spring,hibernate等等。

从几年前的java1.5开始,java新增了泛型、注解、并发的功能。这些功能都是java高大上的功能。到现在还在广泛的使用,

说明经典的重要的知识经的住时间的考验。最新的技术不都是很重要的知识。

 

注解用到两个反射方法

getDeclaredMethods() 和getAnnotation(),他们都属于AnnotatedElement接口(Class,Method与Field等类都实现了该接口)

Annotation[] anns = field.getDeclaredAnnotations();

Annotation[] anns = field.getAnnotations();

这两个方法有什么区别?

虽然返回的类型是一样的,但是getDeclaredAnnotations返回的是具体的声明的注解;

field.getAnnotations()使用的Field类的父类的AccessibleObject的getAnnotations方法;getAnnotations方法返回getDeclaredAnnotations方法;

getDeclaredAnnotations方法的内容是throw new AssertionError("All subclasses should override this method");

即是AccessibleObject类的所有子类必须覆盖这个方法。即正确的调用方式应该是调用子类Field的getDeclaredAnnotations方法。

 

 

 

 

/** *  */package annotation.database;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * @author Administrator * */@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface Constraints {    boolean primaryKey() default false;    boolean allowNull() default true;    boolean unique() default false;}

 

 

 

/** *  */package annotation.database;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * @author Administrator * */@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface DBTable {    public String name() default "";}

 

 

/** *  */package annotation.database;/** * @author Administrator * */@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;    public String getFirstName() {        return firstName;    }    public String getLastName() {        return lastName;    }    public Integer getAge() {        return age;    }    public String getHandle() {        return handle;    }    public String toString() {        return handle;    }}

 

package annotation.database;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * @author Administrator * */@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface SQLInteger {    String name() default "";    Constraints constraints() default @Constraints;}

 

/** *  */package annotation.database;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * @author Administrator * */@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface SQLString {    int value() default 0;    String name() default "";    Constraints constraints() default @Constraints;}

 

/** *  */package annotation.database;import java.lang.annotation.Annotation;import java.lang.reflect.Field;import java.util.ArrayList;import java.util.List;/** * @author Administrator * */public class TableCreator {    /**     * @param args     * @throws ClassNotFoundException     */    public static void main(String[] args) throws Exception {        if (args.length < 1) {            System.out.println("arguments:annotated classes");            System.exit(0);        }        for (String className : args) {            Class<?> cl = Class.forName(className);            DBTable dbTable = cl.getAnnotation(DBTable.class);            if (dbTable == null) {                System.out.println("No DBTable annotations in class "                        + className);                continue;            }            String tableName = dbTable.name();            if (tableName.length() < 1) {                tableName = cl.getName().toUpperCase();            }            List<String> columnDefs = new ArrayList<String>();            for (Field field : cl.getDeclaredFields()) {                String columnName = null;                Annotation[] anns = field.getDeclaredAnnotations();                field.getAnnotations();                if (anns.length < 1) {                    continue;                }                if (anns[0] instanceof SQLInteger) {                    SQLInteger sInt = (SQLInteger) anns[0];                    if (sInt.name().length() < 1) {                        columnName = field.getName().toUpperCase();                    } else {                        columnName = sInt.name();                    }                    columnDefs.add(columnName + " INT"                            + getConstraints(sInt.constraints()));                }                if (anns[0] instanceof SQLString) {                    SQLString sString = (SQLString) anns[0];                    if (sString.name().length() < 1) {                        columnName = field.getName().toUpperCase();                    } else {                        columnName = sString.name();                    }                    columnDefs.add(columnName + " VARCHAR(" + sString.value()                            + ")" + getConstraints(sString.constraints()));                }            }            StringBuilder createCommand = new StringBuilder("CREATE TABLE"                    + tableName + "(");            for (String columnDef : columnDefs) {                createCommand.append("\n " + columnDef + ",");            }            String tableCreate = createCommand.substring(0,                    createCommand.length() - 1)                    + ");";            System.out.println("Table Creation SQL for " + className                    + " is :\n" + tableCreate);        }    }    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;    }}

 

 

 

 

 

 

Java编程思想-注解生成外部例子代码