Java & Groovy & Scala & Kotlin - 33.Reflect 與 Annotation

Overview

本章主要介紹在實際編程中非常重要的反射和注解兩大特性。

Java

注解

注解主要用于標示元數(shù)據(jù)。Java 中聲明一個注解使用符號 @interface

創(chuàng)建一個注解

例:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Bean {
    String name();
}

以上創(chuàng)建了一個名為 Bean 的注解。該注解上使用了標示此自定義注解的兩個 JVM 的內(nèi)置注解:RetentionTarget

Rentention 表示應該將該注解信息保存在哪里,有 RUNTIMECLASSSOURCE 三種。其中 CLASS 為默認值,只有標示為 RUNTIME 的注解才可以被反射。

Target 表示應該將注解放在哪里,有 TYPEFIELDMETHODPARAMETER 等幾種。即聲明為 TYPE 時可以將注解放在類或接口上,聲明為 FIELD 則只能方法屬性上。

以上創(chuàng)建的注解中還包含有一個屬性 name,在使用該注解時必須同時定義此屬性。如果使用 String name() default ""; 替代的話則可以不定義此屬性而使用默認值。

使用注解

創(chuàng)建三個注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Bean {
    String name();
}

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface BeanField {
}

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

以上創(chuàng)建的注解 Bean 使用時必須定義 name 屬性,而 BeanMethodalias 屬性由于有默認值空字符串,所以定義時可以省略 alias 屬性。

定義一個使用以上注解的類

@Bean(name = "t_person")
class Person {

    public Person() {
    }

    public Person(int age) {
        this.age = age;
    }

    @BeanField
    private int age;

    @BeanMethod(alias = "trueAge")
    public int getAge() {
        return age;
    }

    public void setAge(final int age) {
        this.age = age;
    }

    @BeanMethod(alias = "hello")
    public void sayHello(String message) {
        System.out.println("hello " + message);
    }
}

反射

所謂的反射即是在運行時獲得類的各種元數(shù)據(jù)(類本身,類中的方法,類中的屬性等)的一種手段。實際開發(fā)中反射主要用于編寫各種工具,我們需要自己編寫反射的情況實際非常少。

類的引用

為了對一個類進行反射需要先獲得類的信息,即獲得類的引用,Java 中需要使用以下方法

Class<?> clazz = Person.class;

方法的引用

方法存在于類中,所以獲得方法的引用前需要先獲得類的引用。

Method setAgeMethod = clazz.getMethod("setAge", int.class);

以上使用了 getMethod() 方法獲得了 Person 類中的 setAge(int) 方法的引用。getMethod() 方法的第一個參數(shù)為方法名,之后接著的為表示方法的參數(shù)列表的變參。

getMethod() 類型還有一個名為 getDeclaredMethod() 的方法,兩者最顯著的區(qū)別是前者只能獲得公開成員,而后者可以獲得私有成員。基本上方法,屬性,注解等的引用都有這兩種方法。

獲得方法的引用后,可以通過 invoke() 執(zhí)行該方法。invoke() 的第一個參數(shù)為需要執(zhí)行該方法的對象,之后接著的為傳入該方法的參數(shù)列表。

Method setAgeMethod = clazz.getMethod("setAge", int.class);
setAgeMethod.invoke(person, 100);
Method getAgeMethod = clazz.getMethod("getAge");
int age = (int) getAgeMethod.invoke(person);
System.out.println("Age is " + age);    //  100

屬性的引用

屬性的引用基本同方法的引用。

Field ageField = clazz.getDeclaredField("age");

通過屬性的引用來獲得屬性的值只需要通過 getXXX() 之類的方法就可以了,該方法參數(shù)為持有該屬性的對象。

ageField.setAccessible(true);
System.out.println("Age is " + ageField.getInt(person));

以上由于 age 在聲明時為私有變量,所以需要先使用 setAccessible() 才能進行訪問。

構(gòu)造方法的引用

構(gòu)造方法的引用也和其它引用差不多,直接看例子就可以了。

Constructor<Person> constructor = (Constructor<Person>) clazz.getConstructor(int.class);
Person person1 = constructor.newInstance(18);
System.out.println("Age is " + person1.getAge());

注解的引用

Bean bean = clazz.getAnnotation(Bean.class);
String name = bean.name();
System.out.println("Name is " + name);  //  t_person

遍歷類的成員

實際開發(fā)中由于反射主要用于編寫工具,所以大部分情況下我們都不知道反射的類的結(jié)構(gòu),所以通常都需要對類的成員進行遍歷并結(jié)合以上的所有方法。下面是一個簡單的例子。

Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
    Annotation[] annotations = field.getDeclaredAnnotations();
    if (annotations == null || annotations.length == 0) continue;
    System.out.println("Find field annotation " + annotations[0].annotationType().getSimpleName());
}

Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
    Annotation[] annotations = method.getDeclaredAnnotations();
    if (annotations == null || annotations.length == 0) continue;
    System.out.println("Find method annotation " + annotations[0].annotationType().getSimpleName());  //  BeanMethod

    BeanMethod beanMethod = (BeanMethod) annotations[0];
    String alias = beanMethod.alias();
    System.out.println("Alias is " + alias);    //  trueAge

    if (method.getName().equals("sayHello")) {
        method.invoke(person, "world");
    }
    System.out.println("====================");
}

Groovy

注解

Groovy 用法同 Java。

創(chuàng)建一個注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Bean {
    String name()
}

使用注解

創(chuàng)建三個注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Bean {
    String name()
}

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
@interface BeanField {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface BeanMethod {
    String alias() default ""
}

定義一個使用以上注解的類

@Bean(name = "t_person")
class Person {

    @BeanField
    def int age

    @BeanMethod(alias = "trueAge")
    def int getAge() {
        age
    }

    def void setAge(int age) {
        this.age = age
    }

    @BeanMethod(alias = "hello")
    def void sayHello(String message) {
        println("hello $message")
    }
}

反射

Groovy 中的反射與 Java 一樣,不過 Groovy 中擁有更強大的元編程,在以后會提起。

類的引用

def clazz = Person.class

方法的引用

def setAgeMethod = clazz.getMethod("setAge", int.class)

執(zhí)行該方法

def setAgeMethod = clazz.getMethod("setAge", int.class)
setAgeMethod.invoke(person, 100)
def getAgeMethod = clazz.getMethod("getAge")
int age = (int) getAgeMethod.invoke(person)
println("Age is " + age)    //  100

除了使用 invoke(),Groovy 還有另一種方式來執(zhí)行方法,使用時看起來有些像 JavaScript 的 eval() 函數(shù)。

person."${setAgeMethod.name}"(20)

屬性的引用

def ageField = clazz.getDeclaredField("age")

獲得屬性的值

ageField.setAccessible(true)
println("Age is " + ageField.getInt(person))

構(gòu)造方法的引用

如果使用構(gòu)造方法的引用則必須先定義需要的構(gòu)造方法,但這樣會喪失了 Groovy 構(gòu)造方法的帶名參數(shù)的功能。

def constructor = clazz.getConstructor(int.class)
def person1 = constructor.newInstance(18)
println("Age is " + person1.getAge())

注解的引用

Bean bean = clazz.getAnnotation(Bean.class)
def name = bean.name()
println("name is " + name)

遍歷類的成員

clazz.declaredFields.findAll {
    it.declaredAnnotations != null && it.declaredAnnotations.size() > 0
}.each {
    println("Find field annotation ${it.annotations[0].annotationType().simpleName}")
}

clazz.declaredMethods.findAll {
    it.declaredAnnotations != null && it.declaredAnnotations.size() > 0
}.each {
    println("Find method annotation ${it.annotations[0].annotationType().simpleName}")

    def alias = (it.annotations[0] as BeanMethod).alias()
    println("Alias is $alias")

    if (it.name == "sayHello") {
        it.invoke(person, "world")
    }
    println("====================")
}

Scala

注解

Scala 大多情況下直接使用 Java 的注解即可。Scala 本身雖然也提供了Scala 風格的注解功能,但功能很弱,完全可以使用 Java 的進行替代。

創(chuàng)建一個注解

Scala 創(chuàng)建注解需要繼承 ClassfileAnnotation 或 StaticAnnotation。前者類似 Java 中的 Runtime,可以被反射,后者則無法被反射。

class Bean(val name: String) extends ClassfileAnnotation

使用注解

創(chuàng)建三個注解

class Bean(val name: String) extends ClassfileAnnotation
class BeanField extends StaticAnnotation
class BeanMethod(val alias: String = "") extends StaticAnnotation

定義一個使用以上注解的類

@Bean(name = "t_person")
class Person {
    @BeanField
    private var privateAge: Int = 0

    @BeanMethod(alias = "trueAge")
    def age_=(pAge: Int) {
      privateAge = pAge
    }

    def age = privateAge

    @BeanMethod
    def sayHello(message: String) = println(s"hello $message")
}

反射

Scala 有自己的反射 Api,功能比 Java 要更豐富,但是個人感覺非常難用,還是直接使用 Java 的更加方便。對 Scala 的 Api 有興趣的可以直接去官網(wǎng)查看文檔。

下面列一個簡單的根據(jù)類生成對象的 Scala 原生 Api 的例子,體驗一下有多難用

val classLoaderMirror = runtimeMirror(getClass.getClassLoader)
val typePerson = typeOf[Person]
val classPerson = typePerson.typeSymbol.asClass
val classMirror = classLoaderMirror.reflectClass(classPerson)
val methodSymbol = typePerson.decl(termNames.CONSTRUCTOR).asMethod
val methodMirror = classMirror.reflectConstructor(methodSymbol)
val p: Person = methodMirror(10).asInstanceOf[Person]
p.age = 16
println(p.age)

Kotlin

注解

Kotlin 用法類似 Java,但還是有很大區(qū)別。

創(chuàng)建一個注解

AnnotationRetention 類似 Java 的 RetentionPolicyAnnotationTarget 類似 Java 的 ElementType,但是由于 Kotlin 的特性,其值有 FIELDPROPERTY_GETTER 等種類。

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@Repeatable
@MustBeDocumented
annotation class Bean(val name: String)

使用注解

創(chuàng)建三個注解

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@Repeatable
@MustBeDocumented
annotation class Bean(val name: String)

@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.FIELD)
annotation class BeanField

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.FUNCTION)
annotation class BeanMethod(val alias: String = "")

定義一個使用以上注解的類

@Bean(name = "t_person")
class Person {
    @BeanField var age: Int = 0
        @BeanMethod(alias = "trueAge") get() = field

    @BeanMethod(alias = "hello") fun sayHello(message: String) {
        println("hello $message")
    }
}

反射

Kotlin 中的反射可以通過符號 :: 直接對各種類和成員進行引用,但是如果想通過字符串進行引用的話就非常麻煩。

類的引用

val clazz = Person::class

函數(shù)的引用

val sayHello = Person::sayHello

執(zhí)行該函數(shù)

println(sayHello.invoke(person, "world"))

就像類中的函數(shù)一樣也可以直接對定義在類外的函數(shù)進行引用,并將該引用作為參數(shù)進行傳遞

fun isOdd(x: Int) = x % 2 != 0
val numbers = listOf(1, 2, 3)
println(numbers.filter(::isOdd))

屬性的引用

var name = Person::age

獲得屬性的值

name.get(person)

同樣也可以對類外的屬性進行引用

var x = 2
println(::x.get())
::x.set(3)
println(x)

構(gòu)造方法的引用

::Person

使用該引用

fun factory(f: () -> Person) {
    val p = f()
}
factory(::Person)

遍歷類的成員

val bean = clazz.annotations.first {
    it.annotationType().typeName == Bean::class.qualifiedName
} as Bean
println("name is ${bean.name}") //  t_person

val properties = clazz.declaredMemberProperties
properties.filter {
    it.annotations.isNotEmpty()
}.forEach {
    println(it.annotations[0].annotationClass.simpleName)
}

val functions = clazz.declaredMemberFunctions
functions.filter {
    it.annotations.isNotEmpty()
}.forEach {
    println(it.name)
    println(it.annotations[0].annotationClass.simpleName)    //  BeanMethod

    val beanMethod = it.annotations[0] as BeanMethod
    println("alias is ${beanMethod.alias}") //  hello
}

Summary

  • 注解使用場景很多,但是一般只要理解內(nèi)置注解的作用,很少需要自己定義注解
  • 反射 Api 大都比較難用,但是實際使用場景并不多

文章源碼見 https://github.com/SidneyXu/JGSK 倉庫的 _33_reflect_annotation 小節(jié)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,546評論 6 533
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,570評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,505評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,017評論 1 313
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,786評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,219評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,287評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,438評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,971評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,796評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,995評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,540評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,230評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,918評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,697評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內(nèi)容

  • 前言 人生苦多,快來 Kotlin ,快速學習Kotlin! 什么是Kotlin? Kotlin 是種靜態(tài)類型編程...
    任半生囂狂閱讀 26,243評論 9 118
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,785評論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,898評論 6 342
  • 文/冬至 11. 山里沒有洗澡的條件,所以我們也只能十五天去縣城一洗,這已經(jīng)是對我們來說最好的條件了。 雖然看起來...
    你好哇冬至閱讀 306評論 0 0
  • 苦悶地周末早晨起來做了半天ID排版,中間出去吃了半碗面條,到了下午三點,實在被文字圖片搞得煩悶,跑到操場上透透氣,...
    aed4dc8369ae閱讀 246評論 0 0