zl程序教程

您现在的位置是:首页 >  后端

当前栏目

一个copyList的Kotlin代码例子:

Kotlin代码 一个 例子
2023-09-14 09:07:21 时间

一个copyList的代码例子:

#Kotlin#

/**
 * 把S的列表copy到D的列表
 */
fun <S, D> copyList(sourceList: List<S>?, clazz: Class<D>): List<D>? {
    if (null == sourceList || sourceList.size == 0) {
        return null
    }
    val destList = ArrayList<D>()
    sourceList.forEach {
        val source = it
        val dest = createInstance(clazz)
        if (dest != null) {
            BeanUtils.copyProperties(source, dest)
            destList.add(dest)
        }
    }
    return destList
}

private fun <T> createInstance(clazz: Class<T>): T? {
    var obj: T?
    obj = try {
        clazz.newInstance()
    } catch (e: Exception) {
        logger.error("createInstance with exception: {}", e.message)
        logger.error("exception: ", e)
        null
    }
    return obj
}