第九章 kotlin反射

325 阅读1分钟

9.1、发射的基本概念

1、反射的依赖

具体版本清查看官网

    implementation "org.jetbrains.kotlin:kotlin-reflect:1.6.10"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.10"

kotlinlang.org/docs/reflec…

2、kotlin反射库

kotlin反射库2.5M,编译后400KB

3、kotlin的一些例子

        // 反射
        // 获取字节码
        val kClass = String::class
        // 转换成java
        val java = kClass.java
        // 抓换成kotlin
        val kotlin = java.kotlin

        // 获得内部的方法
        val mapCls = Map::class
        // 拿到类里面申明的属性,扩展方法拿不到
        val firstOrNull = mapCls.declaredMemberProperties.firstOrNull()

        // 获得反射对应的例子
        B::class.objectInstance?.hello()

9.2、获取泛型实参

1、获得接口的泛型实参

package com.example.demo.activity

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.example.demo.R
import com.example.demo.util.LogUtil
import kotlin.reflect.full.declaredFunctions

class Test4Activity : AppCompatActivity() {

    val TAG: String = "Test4Activity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test4)

        // 获取接口的泛型参数
        Api::class.declaredFunctions.first { it.name == "getUser" }
            .returnType.arguments.forEach { Log.e(TAG, it.toString()) }

        // 获得函数引用
        Api::getUser.returnType.arguments.forEach { Log.e(TAG, it.toString()) }
        
    }

}

interface Api {
    fun getUser(): List<UserDTO>
}

class UserDTO {}

2、获得父类的泛型实参

package com.example.demo.activity

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.example.demo.R
import com.example.demo.util.LogUtil
import kotlin.reflect.full.declaredFunctions

class Test4Activity : AppCompatActivity() {

    val TAG: String = "Test4Activity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test4)

        val subType = SubType()
        val typeParameter = subType.typeParameter
        Log.e(TAG, typeParameter.toString())

    }

}

abstract class SuperType<T> {
    val typeParameter by lazy {
        // this表示子类,父类只有一个,所以用first获取
        // 然后获取arguments来获取参数
        this::class.supertypes.first().arguments.first().type
    }
}

class SubType : SuperType<UserDTO>() {

}

class UserDTO {}

打印结果如下:

 com.example.demo.activity.UserDTO