Overview
本章主要介紹在實(shí)際編程中非常重要的反射和注解兩大特性。
Java
注解
注解主要用于標(biāo)示元數(shù)據(jù)。Java 中聲明一個(gè)注解使用符號(hào) @interface。
創(chuàng)建一個(gè)注解
例:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Bean {
String name();
}
以上創(chuàng)建了一個(gè)名為 Bean 的注解。該注解上使用了標(biāo)示此自定義注解的兩個(gè) JVM 的內(nèi)置注解:Retention 和 Target。
Rentention 表示應(yīng)該將該注解信息保存在哪里,有 RUNTIME,CLASS,SOURCE 三種。其中 CLASS 為默認(rèn)值,只有標(biāo)示為 RUNTIME 的注解才可以被反射。
Target 表示應(yīng)該將注解放在哪里,有 TYPE,FIELD,METHOD,PARAMETER 等幾種。即聲明為 TYPE 時(shí)可以將注解放在類(lèi)或接口上,聲明為 FIELD 則只能方法屬性上。
以上創(chuàng)建的注解中還包含有一個(gè)屬性 name,在使用該注解時(shí)必須同時(shí)定義此屬性。如果使用 String name() default ""; 替代的話(huà)則可以不定義此屬性而使用默認(rèn)值。
使用注解
創(chuàng)建三個(gè)注解
@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 使用時(shí)必須定義 name 屬性,而 BeanMethod 的 alias 屬性由于有默認(rèn)值空字符串,所以定義時(shí)可以省略 alias 屬性。
定義一個(gè)使用以上注解的類(lèi)
@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);
}
}
反射
所謂的反射即是在運(yùn)行時(shí)獲得類(lèi)的各種元數(shù)據(jù)(類(lèi)本身,類(lèi)中的方法,類(lèi)中的屬性等)的一種手段。實(shí)際開(kāi)發(fā)中反射主要用于編寫(xiě)各種工具,我們需要自己編寫(xiě)反射的情況實(shí)際非常少。
類(lèi)的引用
為了對(duì)一個(gè)類(lèi)進(jìn)行反射需要先獲得類(lèi)的信息,即獲得類(lèi)的引用,Java 中需要使用以下方法
Class<?> clazz = Person.class;
方法的引用
方法存在于類(lèi)中,所以獲得方法的引用前需要先獲得類(lèi)的引用。
Method setAgeMethod = clazz.getMethod("setAge", int.class);
以上使用了 getMethod() 方法獲得了 Person 類(lèi)中的 setAge(int) 方法的引用。getMethod() 方法的第一個(gè)參數(shù)為方法名,之后接著的為表示方法的參數(shù)列表的變參。
與
getMethod()類(lèi)型還有一個(gè)名為getDeclaredMethod()的方法,兩者最顯著的區(qū)別是前者只能獲得公開(kāi)成員,而后者可以獲得私有成員?;旧戏椒?,屬性,注解等的引用都有這兩種方法。
獲得方法的引用后,可以通過(guò) invoke() 執(zhí)行該方法。invoke() 的第一個(gè)參數(shù)為需要執(zhí)行該方法的對(duì)象,之后接著的為傳入該方法的參數(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");
通過(guò)屬性的引用來(lái)獲得屬性的值只需要通過(guò) getXXX() 之類(lèi)的方法就可以了,該方法參數(shù)為持有該屬性的對(duì)象。
ageField.setAccessible(true);
System.out.println("Age is " + ageField.getInt(person));
以上由于 age 在聲明時(shí)為私有變量,所以需要先使用 setAccessible() 才能進(jìn)行訪問(wèn)。
構(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
遍歷類(lèi)的成員
實(shí)際開(kāi)發(fā)中由于反射主要用于編寫(xiě)工具,所以大部分情況下我們都不知道反射的類(lèi)的結(jié)構(gòu),所以通常都需要對(duì)類(lèi)的成員進(jìn)行遍歷并結(jié)合以上的所有方法。下面是一個(gè)簡(jiǎn)單的例子。
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)建一個(gè)注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Bean {
String name()
}
使用注解
創(chuàng)建三個(gè)注解
@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 ""
}
定義一個(gè)使用以上注解的類(lèi)
@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 一樣,不過(guò) Groovy 中擁有更強(qiáng)大的元編程,在以后會(huì)提起。
類(lèi)的引用
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 還有另一種方式來(lái)執(zhí)行方法,使用時(shí)看起來(lái)有些像 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)造方法,但這樣會(huì)喪失了 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)
遍歷類(lèi)的成員
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 風(fēng)格的注解功能,但功能很弱,完全可以使用 Java 的進(jìn)行替代。
創(chuàng)建一個(gè)注解
Scala 創(chuàng)建注解需要繼承 ClassfileAnnotation 或 StaticAnnotation。前者類(lèi)似 Java 中的 Runtime,可以被反射,后者則無(wú)法被反射。
class Bean(val name: String) extends ClassfileAnnotation
使用注解
創(chuàng)建三個(gè)注解
class Bean(val name: String) extends ClassfileAnnotation
class BeanField extends StaticAnnotation
class BeanMethod(val alias: String = "") extends StaticAnnotation
定義一個(gè)使用以上注解的類(lèi)
@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 要更豐富,但是個(gè)人感覺(jué)非常難用,還是直接使用 Java 的更加方便。對(duì) Scala 的 Api 有興趣的可以直接去官網(wǎng)查看文檔。
下面列一個(gè)簡(jiǎn)單的根據(jù)類(lèi)生成對(duì)象的 Scala 原生 Api 的例子,體驗(yàn)一下有多難用
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 用法類(lèi)似 Java,但還是有很大區(qū)別。
創(chuàng)建一個(gè)注解
AnnotationRetention 類(lèi)似 Java 的 RetentionPolicy。AnnotationTarget 類(lèi)似 Java 的 ElementType,但是由于 Kotlin 的特性,其值有 FIELD,PROPERTY_GETTER 等種類(lèi)。
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@Repeatable
@MustBeDocumented
annotation class Bean(val name: String)
使用注解
創(chuàng)建三個(gè)注解
@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 = "")
定義一個(gè)使用以上注解的類(lèi)
@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 中的反射可以通過(guò)符號(hào) :: 直接對(duì)各種類(lèi)和成員進(jìn)行引用,但是如果想通過(guò)字符串進(jìn)行引用的話(huà)就非常麻煩。
類(lèi)的引用
val clazz = Person::class
函數(shù)的引用
val sayHello = Person::sayHello
執(zhí)行該函數(shù)
println(sayHello.invoke(person, "world"))
就像類(lèi)中的函數(shù)一樣也可以直接對(duì)定義在類(lèi)外的函數(shù)進(jìn)行引用,并將該引用作為參數(shù)進(jìn)行傳遞
fun isOdd(x: Int) = x % 2 != 0
val numbers = listOf(1, 2, 3)
println(numbers.filter(::isOdd))
屬性的引用
var name = Person::age
獲得屬性的值
name.get(person)
同樣也可以對(duì)類(lèi)外的屬性進(jìn)行引用
var x = 2
println(::x.get())
::x.set(3)
println(x)
構(gòu)造方法的引用
::Person
使用該引用
fun factory(f: () -> Person) {
val p = f()
}
factory(::Person)
遍歷類(lèi)的成員
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
- 注解使用場(chǎng)景很多,但是一般只要理解內(nèi)置注解的作用,很少需要自己定義注解
- 反射 Api 大都比較難用,但是實(shí)際使用場(chǎng)景并不多
文章源碼見(jiàn) https://github.com/SidneyXu/JGSK 倉(cāng)庫(kù)的 _33_reflect_annotation 小節(jié)