目 录CONTENT

文章目录

Kotlin 实现接口时,省略不需要重写的空方法

Stars-one
2025-01-21 / 0 评论 / 0 点赞 / 3 阅读 / 3371 字

Kotlin中如果要实现某个接口,需要将接口的全部方法都重写(即使我们不需要重写)

如下面代码:

//假设我们只用到重写的onActivityCreated方法,剩余的其他方法都是空的,但这个时候我们想直接将他们省略不写,眼不见心不烦,怎么做呢?
val callback  = object : ActivityLifecycleCallbacks {
	override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
		//相关逻辑
	}

	override fun onActivityStarted(activity: Activity) {
	}

	override fun onActivityResumed(activity: Activity) {
	}

	override fun onActivityPaused(activity: Activity) {
	}

	override fun onActivityStopped(activity: Activity) {
	}

	override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
	}

	override fun onActivityDestroyed(activity: Activity) {
	}


}

有2种方法可

下面以Android里的ActivityLifecycleCallbacks接口为例:

  1. 使用个抽象类所有方法都重写为空方法(我们常见的做法)
abstract class DefaultCallBack :Application.ActivityLifecycleCallbacks{
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
    }

    override fun onActivityStarted(activity: Activity) {
    }

    override fun onActivityResumed(activity: Activity) {
    }

    override fun onActivityPaused(activity: Activity) {
    }

    override fun onActivityStopped(activity: Activity) {
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
    }

    override fun onActivityDestroyed(activity: Activity) {
    }
}
//具体的使用
val dj = object : DefaultCallBack() {
	override fun onActivityDestroyed(activity: Activity) {

	}
}

上面的做法虽然简单,但得每此都创建一个新的类,还是有些繁琐,我们可以使用下面的代理方法

  1. 使用代理
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Proxy

internal inline fun <reified T : Any> noOpDelegate(): T {
    val javaClass = T::class.java
    return Proxy.newProxyInstance(
        javaClass.classLoader, arrayOf(javaClass), NO_OP_HANDLER
    ) as T
}

private val NO_OP_HANDLER = InvocationHandler { _, _, _ ->
    // no op
}

//具体的使用示例
val callBacks  = object : Application.ActivityLifecycleCallbacks by noOpDelegate() {
	override fun onActivityDestroyed(activity: Activity) {
		
	}
}

参考

0

评论区