注释必须调用super的接口函数

时间:2016-10-20 11:18:49

标签: kotlin

我正在创建界面,其中的一些功能有一个正文。 这是必需的,实现此接口的类必须在执行其他代码之前调用super覆盖函数。 我怎么能这样做?

interface Watcher {
    fun funWithoutBody()

    fun startWatching() {
        //do some important stuff which must be called
    }
}

3 个答案:

答案 0 :(得分:9)

我意外地发现了我正在寻找的东西。它是@CallSuper包中提供的android.support.annotation注释。 Docs

  

使用@CallSuper批注验证重写方法   调用方法的超级实现。以下示例   注释onCreate()方法以确保任何重写方法   实现调用super.onCreate():

@CallSuper
protected fun onCreate(savedInstanceState: Bundle?) {
}

答案 1 :(得分:3)

Android Studio / IntelliJ IDEA does this sort of thing in some cases but it isn't done through annotations but through code inspection.

e.g. MissingSuperCall is an Android Lint Check for which IntelliJ IDEA supports (Integration with Android Lint tool in IntelliJ IDEA 11.1 | IntelliJ IDEA Blog).

You can create your own custom inspection if you are using Android Studio or IntelliJ IDEA: IntelliJ IDEA 2016.2 Help :: Creating Custom Inspections.

答案 2 :(得分:2)

你可以将startWatching抽象化并在另一个函数中调用它。 E.g:

interface Watcher {
    fun funWithoutBody()

    fun userDefinedStartWatching()

    fun startWatching() {
        //insert code you'd normally want to be called when using super()
        userDefinedStartWatching()
    }
}