Kotlin中KClass反射
Kotlin是函数式编程语言,它有一些独有的特性,例如,在Kotlin中的Property对应Java的Field以及对应的getter/setter,而函数本身也具有类型,
也可以作为变量保存。
要使用Kotlin的反射Api,需要获取对应的KClass对象,可以通过以下方式:
1.类名::class
var class=Country::class
2.对象.javaclass.kotlin
var class=country.javaclass.kotlin
添加依赖:
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
否则会报
KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar in the classpath
KClass是一个泛型接口,它的定义如下:
public actual interface KClass<T : Any> : KDeclarationContainer, KAnnotatedElement, KClassifier {
//返回类的名字
public actual val simpleName: String?
/**
*返回类的全包名
*/
public val qualifiedName: String?
/**
* All functions and properties accessible in this class, including those declared in this class
* and all of its superclasses. Does not include constructors.
返回这个类可以访问的所有函数和属性,包括继承自基类的,但是不包括构造函数
*/
override val members: Collection<KCallable<*>>
/**
* All constructors declared in this class.
返回这个类的所有构造器
*/
public val constructors: Collection<KFunction<T>>
/**
* All classes declared inside this class. This includes both inner and static nested classes.
返回这个类中定义的其他类 ,包括内部类和嵌套类
*/
public val nestedClasses: Collection<KClass<*>>
/**
* The instance of the object declaration, or `null` if this class is not an object declaration.
如果这个类声明为object,则返回其实例,否则返回null
*/
public val objectInstance: T?
/**
* Returns `true` if [value] is an instance of this class on a given platform.
判断一个对象是否为此类的实例
和对象is类名作用一样,如country is Country
*/
@SinceKotlin("1.1")
public fun isInstance(value: Any?): Boolean
/**
* The list of type parameters of this class. This list does *not* include type parameters of outer classes.
返回这个类的泛型列表
*/
@SinceKotlin("1.1")
public val typeParameters: List<KTypeParameter>
/**
* The list of immediate supertypes of this class, in the order they are listed in the source code.
以列表的形式依次显示其直接基类
*/
@SinceKotlin("1.1")
public val supertypes: List<KType>
/**
* The list of the immediate subclasses if this class is a sealed class, or an empty list otherwise.
*/
@SinceKotlin("1.3")
public val sealedSubclasses: List<KClass<out T>>
/**
* Visibility of this class, or `null` if its visibility cannot be represented in Kotlin.
返回这个类的可见性
*/
@SinceKotlin("1.1")
public val visibility: KVisibility?
/**
* `true` if this class is `final`.
这个类是否是final类(在kotlin中,类默认是final的 除非这个类声明为open或者abstract)
*/
@SinceKotlin("1.1")
public val isFinal: Boolean
/**
* `true` if this class is `open`.
*/
@SinceKotlin("1.1")
public val isOpen: Boolean
/**
* `true` if this class is `abstract`.
*/
@SinceKotlin("1.1")
public val isAbstract: Boolean
/**
* `true` if this class is `sealed`.
* See the [Kotlin language documentation](https://kotlinlang.org/docs/reference/sealed-classes.html)
* for more information.
判断是否为密封类
用sealed修饰,其子类只能在其内部定义
*/
@SinceKotlin("1.1")
public val isSealed: Boolean
/**
* `true` if this class is a data class.
* See the [Kotlin language documentation](https://kotlinlang.org/docs/reference/data-classes.html)
* for more information.
*/
@SinceKotlin("1.1")
public val isData: Boolean
/**
* `true` if this class is an inner class.
* See the [Kotlin language documentation](https://kotlinlang.org/docs/reference/nested-classes.html#inner-classes)
* for more information.
判断类是否为内部类(嵌套类为nest ,不算)
*/
@SinceKotlin("1.1")
public val isInner: Boolean
/**
* `true` if this class is a companion object.
* See the [Kotlin language documentation](https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects)
* for more information.
*/
@SinceKotlin("1.1")
public val isCompanion: Boolean
/**
* Returns `true` if this [KClass] instance represents the same Kotlin class as the class represented by [other].
* On JVM this means that all of the following conditions are satisfied:
*
* 1. [other] has the same (fully qualified) Kotlin class name as this instance.
* 2. [other]'s backing [Class] object is loaded with the same class loader as the [Class] object of this instance.
* 3. If the classes represent [Array], then [Class] objects of their element types are equal.
*
* For example, on JVM, [KClass] instances for a primitive type (`int`) and the corresponding wrapper type (`java.lang.Integer`)
* are considered equal, because they have the same fully qualified name "kotlin.Int".
*/
override fun equals(other: Any?): Boolean
override fun hashCode(): Int
}
函数和属性具有了共同的接口KCallable,允许你调用其Call方法来使用函数或者访问属性的getter:
class DVT {
fun test()
{
val su = Person("su",24)
val clazz = su.javaClass.kotlin
val list = clazz.members
for(calls in list)
{
when(calls.name)
{
"name" -> print("name is"+calls.call(su))
"age" -> print("age is"+calls.call(su))
"selfDescribe" -> calls.call(su)
}
}
}
}
data class Person(val name : String,var age : Int)
{
fun selfDescribe() : String
{
return "My name is $name,I am $age years old"
}
}
需要注意,call这个方法的参数类型是vararg Any?,如果你用错误的类型实参(数量不一致或者类型不一致)去调用是会报错的,为了避免这种情况,你可以用更具体的方式去调用这个函数。
class DVT {
fun test()
{
val su = Person("su",24)
val clazz = su.javaClass.kotlin
val function1 = Person::selfDescribe
val function2 = Person::grow
function1.invoke(su)
function2.invoke(su,1)
}
}
data class Person(val name : String,var age : Int)
{
fun selfDescribe() : String
{
return "My name is $name,I am $age years old"
}
fun grow(a : Int) : Int
{
age+=a
return age
}
}
function1的类型是KFunction0<String>,function2的类型是KFunction1<Int,Int>,像KFunctionN这样的接口代表了不同数量参数的参数,
它们都继承了KFunction并添加了一个invoke成员,它拥有数量刚好的参数,包含参数和返回参数
这种类型称为编译器生成的类型,你不能找到它们的声明,你可以使用任意数量参数的函数接口(而不是先声明一万个不同参数数量的接口)
对于call函数,它是对于所有类型通用的手段,但是不保证安全性。
你也可以反射调用属性的getter和setter:
val ageP = Person::age
//通过setter-call调用(不安全)
ageP.setter.call(24)
//通过set()调用(安全)
ageP.set(su,24)
//通过getter-call调用(不安全)
ageP.getter.call()
//通过get调用(安全)
ageP.get(su)
所有属性都是KProperty1的实例,它是一个泛型类KProperty1<R,T>,其中R为接收者类型(文中的Person类),T为属性类型(文中为Int),
这样就保证了你对正确类型的接收者调用其方法。
其子类KMutableProperty代表var属性
网友评论