组件化时,组件需要暴露一些接口给外部。
而当组件的实现没有被装载时,我们希望调用者不用进行逻辑判断,执行代码时自动会执行一段空实现,当我们有海量接口时,自动创建空实现也许是一种省事的方法。
抄下面代码就完事了。
object NoOpImplement {
private const val TAG = "NoOpImplement"
private val classMap = mutableMapOf<Class<out Any>, Any>()
fun <T : Any> get(clazz: Class<T>): T {
val found = classMap[clazz]
return (if (found == null) {
val impl = Proxy.newProxyInstance(clazz.classLoader,
arrayOf<Class<*>>(clazz), NoOpInvocationHandler)
classMap[clazz] = impl
impl
} else {
found
}) as T
}
object NoOpInvocationHandler : InvocationHandler {
override operator fun invoke(o: Any?, method: Method, objects: Array<Any?>?): Any? {
val type: Type = method.returnType
val result: Any? = when {
Boolean::class.javaPrimitiveType == type -> {
false
}
Byte::class.javaPrimitiveType == type -> {
0.toByte()
}
Char::class.javaPrimitiveType == type -> {
0.toChar()
}
Short::class.javaPrimitiveType == type -> {
0.toShort()
}
Int::class.javaPrimitiveType == type -> {
0
}
Long::class.javaPrimitiveType == type -> {
0L
}
Float::class.javaPrimitiveType == type -> {
0.0f
}
Double::class.javaPrimitiveType == type -> {
0.0
}
else -> null
}
Log.v(TAG, "invoke no-op ${method.name} $result")
return result
}
}
}