argonath88
argonath88

Reputation: 453

How to auto call function in Kotlin for every function call within a class

I have a class with multiple functions

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

    fun two() {
        // do something
    }

    fun three() {
        // do something
    }
}

How can I trigger a call to a Logger object that I have, so that in the logs I can see all functions accessed or called, without explicitly placing the log call on every function to keep the code clean. I'm trying to keep a full log trace of all functions called within a service api call, but I don't want to have something like this

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

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

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

Upvotes: 3

Views: 2028

Answers (2)

Michiel Leegwater
Michiel Leegwater

Reputation: 1180

In Java I would write an IvocationHandler to create a dynamic proxy. See this question

Upvotes: 1

gidds
gidds

Reputation: 18597

You can't do it in plain Kotlin.  But this is exactly the sort of thing Aspect-Oriented Programming was intended for.

I haven't used it myself, but if you want to do it in Kotlin, you might look at Spring AOP.  See also discussions here and this question.

Upvotes: 2

Related Questions