反射公共类

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
        }
    }

 

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