Java Annotation Overview詳解
JAVA注解概述:
1. 注解是給編譯器看的,這不同于注釋
2. 三個基本的注解:
@Override 告訴編譯器這是在覆寫方法
@Deprecated 告訴編譯器該方法過時了
@SuppressWarnings("unchecked") 不要警告
= (value={"unchecked"})
3. 注解可以用來替代傳統(tǒng)的配置文件
4. JDK5 開始,Java增加了對元數(shù)據(jù)(MetaData)的支持,即Annotation。
自定義注解和反射注解
自定義注解:
1. 新建annotation:(比接口的定義只多了個@符號)
public @interface myAnnotation {
//屬性
String who();
int age();
String gender();
}
2. 設(shè)置帶默認值的注解
public @interface YouAnnotation {
String who() default "tom";
int age() default 0;
String gender() default "female";
}
3. 數(shù)組情況
public @interface TheyAnnotation {
String[] value(); //一定要有()
}
元Annotation / MetaAnnotation
用來修飾Annotation的。(可以查看@Override的源代碼)
@Retention 注解策略,用于指定該Annotation可以保留的域
RetentionPolicy.CLASS
在字節(jié)碼級別有,在運行級別不可見(默認)
RetentionPolicy.RUNTIME
三個層級均可見,運行時可以反射
RetentionPolicy.SOURCE 只在源碼級別上可用,在字節(jié)碼級別不可見
@Target 指定注解可以被用在哪些范圍上
@Documented 寫入文檔,在使用javadoc命令寫入html文檔時,該注解一同被寫入
@Inherited 可繼承性,繼承該類的子類依然具有父類該注解的特性
ex.反射注解的方式執(zhí)行連接數(shù)據(jù)庫操作:
定義注解如下:
//讓一個注解可以在運行時可以被反射
@Retention(RetentionPolicy.RUNTIME)
public @interface DbInfo {
String driver() default "com.mysql.jdbc.Driver";
String url() default "url = jdbc:mysql://localhost:3306/academic";
String password() default "1234";
String username() default "root";
}
反射注解:
@DbInfo
public static Connection getConnection() throws Exception{
//取得該類的字節(jié)碼
Class clazz = Demo2.class;
//取得該類中名為getConnection()的公共方法
//參數(shù)1:方法名
//參數(shù)2:方法類型參數(shù)對應的字節(jié)碼對象,沒有的話,即null
Method method = clazz.getMethod("getConnection", null);
//通過該方法,取得該方法上定義的注解
DbInfo dbInfo = method.getAnnotation(DbInfo.class);
String driver = dbInfo.driver();
String url = dbInfo.url();
String user = dbInfo.username();
String password = dbInfo.password();
Class.forName(driver);
return DriverManager.getConnection(url, user, password);
}
相關(guān)文章
SpringBoot3.x版本與Mybatis-Plus不兼容問題
當使用3.x版本的SpringBoot結(jié)合Mybatis-Plus時版本不兼容就會報錯,本文就來介紹一下這個問題的解決方法,感興趣的可以了解一下2024-03-03mybatis多數(shù)據(jù)源動態(tài)切換的完整步驟
這篇文章主要給大家介紹了關(guān)于mybatis多數(shù)據(jù)源動態(tài)切換的完整步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11Redisson分布式信號量RSemaphore的使用超詳細講解
這篇文章主要介紹了Redisson分布式信號量RSemaphore的使用,基于Redis的Redisson的分布式信號量RSemaphore采用了與java.util.concurrent.Semaphore相似的接口和用法2023-02-02spring cloud gateway整合sentinel實現(xiàn)網(wǎng)關(guān)限流
這篇文章主要介紹了spring cloud gateway整合sentinel實現(xiàn)網(wǎng)關(guān)限流,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-01-01