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)置注解:Retention
和 Target
。
Rentention
表示應該將該注解信息保存在哪里,有 RUNTIME
,CLASS
,SOURCE
三種。其中 CLASS
為默認值,只有標示為 RUNTIME
的注解才可以被反射。
Target
表示應該將注解放在哪里,有 TYPE
,FIELD
,METHOD
,PARAMETER
等幾種。即聲明為 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
屬性,而 BeanMethod
的 alias
屬性由于有默認值空字符串,所以定義時可以省略 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 的 RetentionPolicy
。AnnotationTarget
類似 Java 的 ElementType
,但是由于 Kotlin 的特性,其值有 FIELD
,PROPERTY_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é)