0
点赞
收藏
分享

微信扫一扫

对象之间,属性批量赋值(替换)/declaredFields /field

一条咸鱼的干货 2022-02-16 阅读 31

通用方法代码


/**
 * [to] 把取的值尝试放到这里
 * [emptyReplacement] 如果取的值是空的,是否也需要替换,默认不需要
 *
 * use : 需要取值的对象.propertyTo(需要把值放入的对象,空值是否也需要替换)
 *
 */
fun Any?.propertyTo(to: Any?, emptyReplacement: Boolean = false) {
    val from = this
    if (from == null || to == null) return
    val fields: Array<Field> = from.javaClass.declaredFields
    try {
        for (field in fields) {
            field.isAccessible = true
            val value: Any? = field.get(from)
            if (emptyReplacement || (null != value && "" != value)) {
                try {
                    val toField: Field = to.javaClass.getDeclaredField(field.name)
		    // 已修正类型对比,处理同名不同类型的属性
                    if (field.type.toString() == toField.type.toString()) {
                        toField.isAccessible = true
                        val toValue = toField.get(to)
                        if (toValue != value) {
                            toField.set(to, value)
                        }
                    }
                } catch (e: NoSuchFieldException) {
                    // 这里是找不到这个property,不用管
                }
            }
        }
    } catch (ignored: Exception) {
    }
}

测试代码

object TestDiff {

    @JvmStatic
    fun main(args: Array<String>) {
        val old = TestEntity(
            "这是旧的", 1,false,1L,1F,1.0, listOf(TestChildrenArrayEntity("旧的", "旧内容")),mutableListOf(TestChildrenArrayEntity("旧的", "旧内容")),
            TestChildrenEntity("旧标题", "旧文本")
        )

        print("旧数据是:")
        print(old)
        print("\n\n")

        val new = TestEntity2(
            "", 2, true, 2L, 2F, 2.0, null, mutableListOf(TestChildrenArrayEntity("新的", "新内容")),
            TestChildrenEntity("新标题", "新文本")
        )

        print("新数据是:")
        print(new)
        print("\n\n")

        print("开始对比替换:\n")
        new.propertyTo(old, true)
        print("结束!\n")

        print("旧数据:")
        print(old)
        print("\n新数据:")
        print(new)
    }
}

data class TestEntity(
    val string: String?,
    val int: Int,
    val boolean: Boolean,
    val long : Long,
    val float: Float,
    val double: Double,
    val list: List<TestChildrenArrayEntity>?,
    val mutableList: MutableList<TestChildrenArrayEntity>?,
    val entity: TestChildrenEntity?
)

data class TestEntity2(
    val strings: String?,
    val ints: Int,
    val booleans: Boolean,
    val long : Long,
    val float: Float,
    val double: Double,
    val list: List<TestChildrenArrayEntity>?,
    val mutableList: MutableList<TestChildrenArrayEntity>?,
    val entity: TestChildrenEntity?
)

data class TestChildrenEntity(val title: String, val content: String)
data class TestChildrenArrayEntity(val title: String, val content: String)

执行日志输出

旧数据是:TestEntity(string=这是旧的, int=1, boolean=false, long=1, float=1.0, double=1.0, list=[TestChildrenArrayEntity(title=旧的, content=旧内容)], mutableList=[TestChildrenArrayEntity(title=旧的, content=旧内容)], entity=TestChildrenEntity(title=旧标题, content=旧文本))

新数据是:TestEntity2(strings=, ints=2, booleans=true, long=2, float=2.0, double=2.0, list=null, mutableList=[TestChildrenArrayEntity(title=新的, content=新内容)], entity=TestChildrenEntity(title=新标题, content=新文本))

开始对比替换:
结束!
旧数据:TestEntity(string=这是旧的, int=1, boolean=false, long=2, float=2.0, double=2.0, list=null, mutableList=[TestChildrenArrayEntity(title=新的, content=新内容)], entity=TestChildrenEntity(title=新标题, content=新文本))
新数据:TestEntity2(strings=, ints=2, booleans=true, long=2, float=2.0, double=2.0, list=null, mutableList=[TestChildrenArrayEntity(title=新的, content=新内容)], entity=TestChildrenEntity(title=新标题, content=新文本))
Process finished with exit code 0

举报

相关推荐

0 条评论