【问题标题】:How to auto call function in Kotlin for every function call within a class如何在 Kotlin 中为类中的每个函数调用自动调用函数
【发布时间】:2019-07-17 01:40:40
【问题描述】:

我有一个具有多种功能的类

class Foo() {
    fun one() {
        //do something
    }

    fun two() {
        // do something
    }

    fun three() {
        // do something
    }
}

如何触发对我拥有的 Logger 对象的调用,以便在日志中我可以看到所有访问或调用的函数,而无需在每个函数上显式调用日志以保持代码干净。我正在尝试对服务 api 调用中调用的所有函数进行完整的日志跟踪,但我不希望有这样的东西

class Foo() {
    fun one() {
        log.call()
        //do something
    }

    fun two() {
        log.call()
        // do something
    }

    fun three() {
        log.call()
        // do something
    }
}

【问题讨论】:

  • 你不能,除非明确写日志语句。
  • 从技术上讲,您可以使用编译器插件,但它们的文档很少而且编写起来很复杂。

标签: kotlin


【解决方案1】:

你不能在普通的 Kotlin 中做到这一点。但这正是 Aspect-Oriented Programming 的目的所在。

我自己没有用过,但是如果你想在 Kotlin 中做,你可以看看Spring AOP。另见讨论herethis 问题。

【讨论】:

  • 谢谢,我去看看
【解决方案2】:

在 Java 中,我会编写一个 IvocationHandler 来创建一个动态代理。见this question

【讨论】:

    猜你喜欢
    • 2019-08-29
    • 1970-01-01
    • 2020-06-25
    • 2018-12-11
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2021-05-13
    相关资源
    最近更新 更多