java 註解 學習

來源:互聯網
上載者:User

標籤:

周末閑來無事,想要研究一下註解方面的知識,曾經看過幾次,都忘記了,這次學習下,而且寫篇文章記錄下,

1、元註解 
元註解是指註解的註解。包含 @Retention @Target @Document @Inherited四種。 
1.1、@Retention: 定義註解的保留原則 
Java代碼 
複製代碼代碼例如以下:


@Retention(RetentionPolicy.SOURCE) //註解僅存在於原始碼中,在class位元組碼檔案裡不包括 
@Retention(RetentionPolicy.CLASS) //預設的保留原則,註解會在class位元組碼檔案裡存在,但執行時無法獲得, 
@Retention(RetentionPolicy.RUNTIME)//註解會在class位元組碼檔案裡存在,在執行時能夠通過反射擷取到 


1.2、@Target:定義註解的作用目標 

Java代碼 
複製代碼代碼例如以下:


@Target(ElementType.TYPE) //介面、類、枚舉、註解 
@Target(ElementType.FIELD) //欄位、枚舉的常量 
@Target(ElementType.METHOD) //方法 
@Target(ElementType.PARAMETER) //方法參數 
@Target(ElementType.CONSTRUCTOR) //建構函式 
@Target(ElementType.LOCAL_VARIABLE)//局部變數 
@Target(ElementType.ANNOTATION_TYPE)//註解 
@Target(ElementType.PACKAGE) ///包 


elementType 能夠有多個,一個註解能夠為類的,方法的,欄位的等等 
1.3、@Document:說明該註解將被包括在javadoc中 
1.4、@Inherited:說明子類能夠繼承父類中的該註解 

2、註解的自己定義 
Java代碼 
複製代碼 代碼例如以下:


@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface HelloWorld { public String name() default ""; } 


3、註解的使用,測試類 

Java代碼 
複製代碼 代碼例如以下:
public class SayHello { @HelloWorld(name = " 小明 ") public void sayHello(String name) { System.out.println(name + "say hello world!"); }//www.heatpress123.net } 


4、解析註解 
java的反射機制能夠協助,得到註解,代碼例如以下: 
Java代碼 
複製代碼 代碼例如以下:

public class AnnTest { public void parseMethod(Class<?> clazz) { Object obj; try { // 通過預設構造方法建立一個新的對象 obj = clazz.getConstructor(new Class[] {}).newInstance( new Object[] {}); for (Method method : clazz.getDeclaredMethods()) { HelloWorld say = method.getAnnotation(HelloWorld.class); String name = ""; if (say != null) { name = say.name(); System.out.println(name); method.invoke(obj, name); } } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { AnnTest t = new AnnTest(); t.parseMethod(SayHello.class); } } 

看到了,非常easy吧,看了java編程思想裡面有個複雜點的範例,我們來溫習一遍,他是用註解實現一個建立資料庫的範例。

先寫一個資料庫名字的註解,用來讀取資料庫的名字:

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

建立一個integer類型的欄位:

package com.bin.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface SQLInteger {String name() default""; //默覺得空Constraints constraints() default @Constraints; //欄位的其它類型定義}

建立一個String 類型的欄位:

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


一些其它定義
package com.bin.annotation;import java.lang.annotation.*;@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface Constraints {boolean primaryKey() default false;boolean allowNull() default true;boolean unique() default false;}

建立一個註解的bean

package com.bin.annotation;@DBTable(name="MEMBER")public class Member {@SQLString(30)String firstName;@SQLString(50) String lastName;@SQLInteger  Integer age;@SQLString(value=30,[email protected](primaryKey=true))String handle;static int memberCount;public String toString(){return handle.toString();}public String getFirstName() {return firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getHandle() {return handle;}public void setHandle(String handle) {this.handle = handle;}}


最後讓我們解析這個註解吧:

package com.bin.annotation;import java.lang.annotation.Annotation;import java.lang.reflect.Field;import java.util.ArrayList;import java.util.List;public class TableCreator {public static void main(String[] args) throws ClassNotFoundException{Class<?> cl =Member.class;DBTable dbtalbe=cl.getAnnotation(DBTable.class);String tableName = dbtalbe.name();if(tableName.length() <1)tableName=cl.getName().toUpperCase();List<String> columnDefs = new ArrayList<String>();for(Field filed : cl.getDeclaredFields()){String columnName = null;Annotation[] anns = filed.getDeclaredAnnotations();if(anns.length < 1)continue;if(anns[0] instanceof SQLInteger){SQLInteger sInt = (SQLInteger)anns[0];if(sInt.name().length() < 1)columnName = filed.getName().toUpperCase();elsecolumnName = 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 = filed.getName().toUpperCase();}elsecolumnName =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)+"\n );";System.out.print(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 註解 學習

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.