Happy
Happy

Reputation: 1855

How to know if a method has been defined in an interface

Given the following code:

interface MyInterface {
    fun foo() {
        // body
    }

    fun bar() {
        // body
    }
}

class MyInterfaceImpl: MyInterface {
    override fun bar() {
        // body
    }
}

I need to know at runtime that bar() has been overridden and foo() hasn't. How to do this using reflection?

Note: java.lang.reflect.Method#getDeclaringClass() always returns MyInterfaceImpl::class.java and java.lang.reflect.Method#isDefault() always returns false. I did not find the solution in KClass.

Upvotes: 2

Views: 291

Answers (2)

Happy
Happy

Reputation: 1855

We can compare MyInterfaceImpl::class.declaredFunctions and MyInterface::class.declaredFunctions.

This property lists all functions declared in this class.

Upvotes: 1

Alexey Soshin
Alexey Soshin

Reputation: 17721

From what I know, where are two ways to achieve that dubious goal.

I'll demonstrate easy one, and discuss idea behind the harder one.

Easy one is based on simply calling toString() on the method:

val functions = MyInterfaceImpl::class.functions

val bar = (functions.toList()[0]) 
val foo = (functions.toList()[2]) 

println(bar.toString()) // fun MyInterfaceImpl.bar(): kotlin.Unit
println(foo.toString()) // fun MyInterface.foo(): kotlin.Unit

As you can see, you can figure if the method was overridden or not by parsing the string.

Harder solution would be to dig into KFunctionImpl, which has delegate member, which has dispatchReceiverParameter

That's a lot of nasty reflection, which is even more nasty, because most of those classes are internal and lazily initialized.

Upvotes: 1

Related Questions