
前言
java里有個神奇的存在,注解,就是那個天天@別人的家伙,它到底是何方神圣啊?
請先給二當家的來個一鍵三連,然后接著耐心的讀下去吧,多謝,
本文由 二當家的白帽子 https://le-yi.blog.csdn.net/ 博客原創,轉載請注明來源,謝謝~
文章目錄
- 前言
- 什么是注解
- 內置的注解
- @Override
- @Deprecated
- @SuppressWarnings
- @SafeVarargs
- @FunctionalInterface
- 元注解
- @Target
- @Documented
- @Inherited
- @Repeatable
- @Retention
- @Native
- 自定義注解
- 注解實戰
- 尾聲
什么是注解
從JDK5開始,Java增加對元資料的支持,也就是注解,注解與注釋是有一定區別的,可以把注解理解為代碼里的特殊標記,這些標記可以在編譯,類加載,運行時被讀取,并執行相應的處理,通過注解開發人員可以在不改變原有代碼和邏輯的情況下在源代碼中嵌入補充資訊,
內置的注解
二當家的發現在 IDE 中如果創建一個類并實作一個介面之后,那些實作介面的方法上面會自動幫我添加 @Override 的標記,
而這個標記就是注解,像@Override這樣JDK內置的注解還有好幾個呢,他們都在java.lang包下面,我們分別看看,
@Override
當子類重寫父類方法時,子類可以加上這個注解,那這有什么什么用?這可以確保子類確實重寫了父類的方法,避免出現低級錯誤,

開始不知道有什么用,直到有一天,我把介面里的這個方法洗掉了,結果就編譯不通過了,

下面是直接在命令列編譯的結果,這回我知道這個標記的作用了,它可以告訴編譯器和閱讀原始碼的人這個方法是覆寫或實作超型別的方法,

@Deprecated
這個注解用于表示某個程式元素類,方法等已過時,當其他程式使用已過時的類,方法時編譯器會給出警告(洗掉線,這個見了不少了吧),

@SuppressWarnings
抑制警告,
package com.secondgod.annotation;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
List objList = intList;
objList.add("二當家的");
}
}
在命令列啟用建議警告的編譯(命令形如 javac -d . -Xlint Test.java ,下文再提到啟用建議警告的編譯,不再贅述解釋),

代碼稍作修改,則可以消除編譯警告,
package com.secondgod.annotation;
import java.util.ArrayList;
import java.util.List;
public class Test {
@SuppressWarnings({"unchecked", "rawtypes"})
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
List objList = intList;
objList.add("二當家的");
}
}
@SafeVarargs
在宣告具有模糊型別(比如:泛型)的可變引數的建構式或方法時,Java編譯器會報unchecked警告,鑒于這些情況,如果程式員斷定宣告的建構式和方法的主體不會對其varargs引數執行潛在的不安全的操作,可使用@SafeVarargs進行標記,這樣的話,Java編譯器就不會報unchecked警告,
package com.secondgod.annotation;
import java.util.List;
public class Test {
public final void test(List<String>... stringLists) {
}
}
在命令列啟用建議警告的編譯,

代碼稍作修改,則可以消除編譯警告,
package com.secondgod.annotation;
import java.util.List;
public class Test {
@SafeVarargs
public final void test(List<String>... stringLists) {
}
}
@FunctionalInterface
函式式介面注解,這個是 Java 1.8 版本引入的新特性,函式式編程很火,所以 Java 8 也及時添加了這個特性,
這個注解有什么用?這個注解保證這個介面只有一個抽象方法,注意這個只能修飾介面,
- 沒有抽象方法的介面
package com.secondgod.annotation;
@FunctionalInterface
public interface Test {
}

- 有超過一個抽象方法的介面
package com.secondgod.annotation;
@FunctionalInterface
public interface Test {
String test1();
String test2();
}

- 只有一個抽象方法的介面
編譯通過,
package com.secondgod.annotation;
@FunctionalInterface
public interface Test {
String test();
}
- 只有一個抽象方法的抽象類
package com.secondgod.annotation;
@FunctionalInterface
public abstract class Test {
public abstract String test();
}

元注解
我們打開@Override的原始碼看下,會發現這個注解的定義上本身還有注解,即注解的注解,人們通常叫他們元注解,元注解是負責對其它注解進行說明的注解,自定義注解時可以使用元注解,

JDK內置的元注解都在java.lang.annotation包下面,

@Target
Target 是目標的意思,@Target 指定了注解運用的地方,
| 取值 | 注解使用范圍 |
|---|---|
| TYPE | 可用于類或者介面上 |
| FIELD | 可用于域/欄位/屬性上 |
| METHOD | 可用于方法上 |
| PARAMETER | 可用于引數上 |
| CONSTRUCTOR | 可用于構造方法上 |
| LOCAL_VARIABLE | 可用于區域變數上 |
| ANNOTATION_TYPE | 可用于注解型別上(被@interface修飾的型別) |
| PACKAGE | 用于記錄java檔案的package資訊 |
| TYPE_PARAMETER | 可用于型別變數的宣告陳述句中 |
| TYPE_USE | 可用于使用型別的任何陳述句中 |
@Documented
用 @Documented 注解修飾的注解類會被 JavaDoc 工具提取成檔案,默認情況下,JavaDoc 是不包括注解的,但如果宣告注解時指定了 @Documented,就會被 JavaDoc 之類的工具處理,所以注解型別資訊就會被包括在生成的幫助檔案中,
@Inherited
Inherited 是繼承的意思,但是它并不是說注解本身可以繼承,而是說如果一個超類被 @Inherited 注解過的注解進行注解的話,那么如果它的子類沒有被任何注解應用的話,那么這個子類就繼承了超類的注解,
@Repeatable
Repeatable 自然是可重復的意思,Java 8 新增加的,它允許在相同的程式元素中重復注解,在需要對同一種注解多次使用時,往往需要借助 @Repeatable 注解,Java 8 版本以前,同一個程式元素前最多只能有一個相同型別的注解,如果需要在同一個元素前使用多個相同型別的注解,則必須使用注解“容器”,
@Retention
@Retention 用于描述注解的生命周期,也就是該注解被保留的時間長短,@Retention 注解中的成員變數(value)用來設定保留策略,value 是 java.lang.annotation.RetentionPolicy 列舉型別,RetentionPolicy 有 3 個列舉常量,如下所示,
| 取值 | 生命周期 |
|---|---|
| SOURCE | 在源檔案中有效(編譯器可以使用) |
| CLASS | 在 class 檔案中有效(編譯器和虛擬機可以使用) |
| RUNTIME | 在運行時有效(編譯器,虛擬機,程式運行時都可以使用) |
@Native
使用 @Native 注解修飾成員變數,則表示這個變數可以被本地代碼參考,常常被代碼生成工具使用,他也在java.lang.annotation包下面,但是我認為他不算是元注解,因為他的使用目標不是注解,

自定義注解
在Spring,Hibernate,Mybatis等框架下都有注解,二當家的也嘗試自定義一個注解,先看下@Override的原始碼吧,
package java.lang;
import java.lang.annotation.*;
/**
* Indicates that a method declaration is intended to override a
* method declaration in a supertype. If a method is annotated with
* this annotation type compilers are required to generate an error
* message unless at least one of the following conditions hold:
*
* <ul><li>
* The method does override or implement a method declared in a
* supertype.
* </li><li>
* The method has a signature that is override-equivalent to that of
* any public method declared in {@linkplain Object}.
* </li></ul>
*
* @author Peter von der Ahé
* @author Joshua Bloch
* @jls 9.6.1.4 @Override
* @since 1.5
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
我們照葫蘆畫瓢也自定義一個,
package com.secondgod.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 測驗注解
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
我們自定義的注解通常都是定義生命周期為 RUNTIME 的,生命周期為 SOURCE 的,需要編譯器的配合,生命周期為 CLASS 的,需要虛擬機的配合,只有程式運行時的行為是我們可以自定義的,
好了,去使用一下這個自定義的注解,
package com.secondgod.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 測驗注解
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
}
/**
* 對自定義注解的測驗
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
public class Test {
@MyAnnotation
private String name;
}
有的注解還帶引數,二當家的也加上,
package com.secondgod.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 測驗注解
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String name();
}
/**
* 對自定義注解的測驗
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
public class Test {
@MyAnnotation(name = "二當家的")
private String name;
}
使用時候賦值必須寫屬性名,像@Target等一些注解賦值的時候就不用寫屬性名,那是因為屬性名是“value”,就可以不用寫,
package com.secondgod.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 測驗注解
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value();
}
/**
* 對自定義注解的測驗
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
public class Test {
@MyAnnotation("二當家的")
private String name;
}
在注解里定義了屬性后,使用的地方必須賦值, 不過可以在注解里定義默認值,使用時就可以不賦值了,
package com.secondgod.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 測驗注解
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value() default "二當家的";
}
/**
* 對自定義注解的測驗
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
public class Test {
@MyAnnotation
private String name;
}
注解里的內容非常的少,顯然他的功能并不在里面實作,所以注解就是個標記,本身并沒有任何功能,那他的功能如何實作呢?
注解實戰
我們用反射和內省配合注解來實作一個小工具,可以自動用環境變數初始化屬性,
package com.secondgod.annotation;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
/**
* 工具類
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
public class MyUtils {
/**
* 私有構造,不可實體化
*/
private MyUtils() {}
/**
* 用于對屬性按斬訓境變數默認初始化
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface EnvironmentVariables {
/**
* 環境變數的key
* @return
*/
String value();
}
/**
* 取得類實體,并用環境變數初始化
*
* @param clazz
* @param <T>
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws java.beans.IntrospectionException
* @throws InvocationTargetException
*/
public static <T> T getInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException, IntrospectionException, InvocationTargetException {
T obj = clazz.newInstance();
setEnvironmentVariables(obj);
return obj;
}
/**
* 為物件屬性按斬訓境變數賦值
*
* @param o
* @throws IllegalAccessException
*/
public static void setEnvironmentVariables(Object o) throws IllegalAccessException, IntrospectionException, InvocationTargetException {
for (Field f : o.getClass().getDeclaredFields()) {
// 利用反射讀取注解
EnvironmentVariables environmentVariables = f.getDeclaredAnnotation(EnvironmentVariables.class);
if (environmentVariables != null) {
// 如果注解存在就讀取環境變數
String value = System.getProperty(environmentVariables.value());
// 利用內省將值寫入
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), o.getClass());
pd.getWriteMethod().invoke(o, value);
}
}
}
}
我們定義一個類用來表示虛擬機的資訊,并且用注解標注屬性欄位,
package com.secondgod.annotation;
import java.text.MessageFormat;
/**
* 虛擬機資訊
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
public class VmInfo {
@MyUtils.EnvironmentVariables(value = "java.vm.version")
private String version;
@MyUtils.EnvironmentVariables(value = "java.vm.vendor")
private String vendor;
@MyUtils.EnvironmentVariables(value = "java.vm.name")
private String name;
@MyUtils.EnvironmentVariables(value = "java.vm.specification.name")
private String specName;
@MyUtils.EnvironmentVariables(value = "java.vm.specification.vendor")
private String specVendor;
@MyUtils.EnvironmentVariables(value = "java.vm.specification.version")
private String specVersion;
@MyUtils.EnvironmentVariables(value = "java.vm.info")
private String info;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpecName() {
return specName;
}
public void setSpecName(String specName) {
this.specName = specName;
}
public String getSpecVendor() {
return specVendor;
}
public void setSpecVendor(String specVendor) {
this.specVendor = specVendor;
}
public String getSpecVersion() {
return specVersion;
}
public void setSpecVersion(String specVersion) {
this.specVersion = specVersion;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String toString() {
return MessageFormat.format("version={0},vendor={1},name={2},specName={3},specVendor={4},specVersion={5},info={6}", version, vendor, name, specName, specVendor, specVendor, info);
}
}
好了,來測驗一下我們的工具吧,
package com.secondgod.annotation;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
/**
* 對自定義注解的測驗
*
* @author 二當家的白帽子 https://le-yi.blog.csdn.net/
*/
public class Test {
public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException, InstantiationException {
VmInfo info1 = new VmInfo();
System.out.println("普通方式實體化后:" + info1);
VmInfo info2 = MyUtils.getInstance(VmInfo.class);
System.out.println("使用我們的小工具實體化后:" + info2);
}
}

內容比較多,圖沒有截全,但是很明顯可以看出我們的小工具符合我們的預期想法,很Nice,
尾聲
在Spring,Hibernate,Mybatis等框架中都有自定義注解,常常用來作為除組態檔之外的另一種配置選擇,他們各有利弊,應該根據實際情況選擇,組態檔修改重啟程式即可,而注解修改顯然只能重新編譯,但是二當家的覺得配置直接放在使用的地方非常方便,可讀性也更好,所以除非是有發布后修改的需求,否則二當家都喜歡用注解,不過用注解就會比較分散,不如組態檔集中,哎,大家仁者見仁,智者見智吧,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/290641.html
標籤:java
上一篇:Java集合你還沒搞明白嗎?看了這篇還不懂就不要學編程了!
下一篇:Java--你的專案資料庫連接配置還在用明文密碼?來幾分鐘了解一下這波純Java撰寫的加解密工具包(附)GitHub原始碼
