反射公共類

object ReflectUtils {

    /**
     * 反射獲取target裏的fieldName對象
     *
     * @param fieldName  對象名稱
     * @param target  反射類實例對象
     * @return 返回fieldName實例對象
     */
    fun getFieldValue(fieldName: String, target: Any): Any {
        try {
            return getFieldValueUnchecked(fieldName, target)
        } catch (e: Exception) {
            throw RuntimeException(e)
        }

    }

    @Throws(NoSuchFieldException::class, IllegalAccessException::class)
    private fun getFieldValueUnchecked(fieldName: String, target: Any): Any {
        val field = findField(fieldName, target.javaClass)

        field.isAccessible = true
        return field.get(target)
    }

    @Throws(NoSuchFieldException::class)
    private fun findField(name: String, clazz: Class<*>): Field {
        var currentClass: Class<*> = clazz
        while (currentClass != Any::class.java) {
            for (field in currentClass.declaredFields) {
                if (name == field.name) {
                    return field
                }
            }

            currentClass = currentClass.superclass
        }

        throw NoSuchFieldException("Field $name not found for class $clazz")
    }

    /**
     *  根據類名獲取到Class對象
     *  注:要是類的全路徑名稱
     */
    fun forName(className: String): Class<*> {
        try {
            return Class.forName(className)
        } catch (e: ClassNotFoundException) {
            throw ClassNotFoundException(e.message)
        }
    }
}

 

 /**
     *  反射獲取target裏的fieldName對象
     *
     *  @param fieldName  對象名稱
     *  @param target  反射類實例對象
     *  @return 返回fieldName實例對象
     *
     */
    fun getFieldValue(fieldName: String?, target: Any?): Any? {
        try {
            fieldName?.let {
                val field = target?.javaClass?.getDeclaredField(fieldName)
                field?.isAccessible = true
                return field?.get(target)
            }
            return null
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
            return null
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
            return null
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章