通用方法代码
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) {
}
}
}
} 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