Android (Kotlin) kotlin-reflect 反射实体类的简单用法

build.gradle

 api "org.jetbrains.kotlin:kotlin-reflect:1.6.10"
//https://github.com/stfalcon-studio/ChatKit
//image-picker:https://github.com/zhihu/Matisse
//api 'pub.devrel:easypermissions:3.0.0'
public class ChatColors {
    public String primary = "";
    public String primaryDark = "";
    public String warning = "";
    public String error = "";
    public String grey1 = "";
    public String grey2 = "";
    public String grey3 = "";
    public String grey4 = "";
    public String grey5 = "";
    public String grey6 = "";
    public String grey7 = "";
    public String grey8 = "";
    public String grey9 = "";
    public String grey10 = "";

    public String white = "";
    public String black = "";
}
class KotlinReflection {
    companion object {
        private var mKotlinReflection: KotlinReflection? = null
        fun getInstance(): KotlinReflection {
            if (mKotlinReflection == null) {
                synchronized(KotlinReflection::class.java) {
                    if (mKotlinReflection == null) {
                        mKotlinReflection = KotlinReflection()
                    }
                }
            }
            return mKotlinReflection!!
        }
    }

    /**
     * Find color name of given style.
     *
     * linkText -> tertiary
     */
    fun findColorName(style: String, chatColors: ChatColors?): Any? {
        chatColors?.let { _colors ->
            val globalColors = getGlobalColorSet(chatColors)
            val colorField = globalColors[style]
            colorField?.let {
                val field = it as? KProperty1
                return field?.get(_colors)
            }
        }
        return null
    }

    /**
     * Store the theme's global Colors in a HashMap for quick lookups
     */
    private val globalColorSet = HashMap>()

    private fun getGlobalColorSet(chatColors: ChatColors?): HashMap> {
        if (globalColorSet.isEmpty()) {
            chatColors?.let {
                val colorFields = it::class.memberProperties
                colorFields.forEach {
                    globalColorSet.set(it.name, it)
                }
            }
        }
        return globalColorSet
    }
}

-----------------------------End-----------------------------

我也是有底线的,感谢您的耐心阅读,欢迎支持与点赞。

你可能感兴趣的:(Android (Kotlin) kotlin-reflect 反射实体类的简单用法)