天天看點

Java程式設計思想-注解生成外部例子代碼注解用到兩個反射方法

如果本文幫助到您,請點選下面的連結,這是本人的網站,以示鼓勵,謝謝!連結絕對安全!

本人的網站

java注解屬于java中高大上的功能,許多開源架構都使用了java注解的功能。比如spring,hibernate等等。

從幾年前的java1.5開始,java新增了泛型、注解、并發的功能。這些功能都是java高大上的功能。到現在還在廣泛的使用,

說明經典的重要的知識經的住時間的考驗。最新的技術不都是很重要的知識。

注解用到兩個反射方法

getDeclaredMethods() 和getAnnotation(),他們都屬于AnnotatedElement接口(Class,Method與Field等類都實作了該接口)

getDeclaredAnnotations和getAnnotations的差別

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方法。

getDeclaredFields和getFields的差別

Class<?>的getFields方法隻傳回公共的字段,如果類沒有公共的字段,那麼傳回長度為0的數組。

Class<?>的getDeclaredFields方法傳回所有聲明的字段(除了繼承的字段):public, protected, default (package) access, and private fields

getDeclaredMethods和getMethods的差別

getMethods方法傳回所有公共的方法,包括從父類和父接口繼承的方法。

getDeclaredMethods方法傳回所有public, protected, default (package) access, and private methods, 但是排除 inherited methods.(繼承的字段)

Java程式設計思想-注解生成外部例子代碼注解用到兩個反射方法
/**
 * 
 */
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;
    }

}      

  如果您覺得本文幫助到您,

請關注新浪微網誌"開心大冒險_往前沖沖沖",以示鼓勵,讓本人寫出更好的文章幫到大家,謝謝!

或者點選右下方的新浪微網誌分享即可。