通过反射获取成员属性键值对的两种方法

先出一个题: 将一个对象里的全部属性名和属性值全部获取,并存进一个hashmap中。

package com.example.kotlin

import java.lang.reflect.Field
import kotlin.reflect.full.memberProperties

class User() {
    var userName: String? = null
    var userPassword: String? = null
    var userSex: String? = null
    var userAge: Int? = 0
    var userAddress: String? = null

    fun reflectMembers(): MutableMap<String, Any> {
        var params = mutableMapOf<String, Any>()
        this.javaClass.kotlin.memberProperties.forEach {
            val value: Any? = it.get(this)
            if (value != null && value.toString().isNotEmpty()) {
                params[it.name] = value
            }
        }
        return params
    }

    fun refelecFields(): MutableMap<String, Any> {
        val fields: Array<Field> = this.javaClass.declaredFields
        var params = mutableMapOf<String, Any>()
        for (field in fields) {
            try {
                field.isAccessible = true
                params[field.name] = field.get(this).toString()
            } catch (e: java.lang.Exception) {
            }
        }
        return params
    }

}

调用

package com.example.kotlin

import okhttp3.internal.notifyAll

class Main {

    /**
     * 匿名函数的使用
     */
    fun test() {
        var service = DemoService()

        service.load<DemoResponse>(DemoBean("abc", 12), DemoReposity(), { ->
            {
                print("没有参数的匿名函数,整个要在{}里面。可以添加->也可以不要。-> 后可以不要{}")
            }
        }, { error ->
            print("只有一个参数的匿名函数,也可以不要error->,默认it为参数")
            print(error)
        }, { rsp: BaseResponse, msg: String ->
            print("有两个以上参数的匿名函数,需要显示写->前面的参数,可以写类型也可以不写")
            print(rsp.toString())
            print(msg)
        })
    }

    fun reflectMembers(){
        var user = User()
        user.userName = "张三"
        user.userPassword = "123456"
        user.userAge = 20
        user.userSex = "male"
        user.userAddress = "BeiJing China"
        var mapMembers = user.reflectMembers() //方法一
        var mapFields = user.refelecFields()   //方法二
    }

}

你可能感兴趣的:(笔记)