Hey everyone. I have a question about Reflection: ...
# announcements
h
Hey everyone. I have a question about Reflection: How to check if a class has overridden a default method from an interface? I have an interface with a default method, and two classes which implement this interface. One of the classes overrides the default method, and the other does not.
Copy code
interface MyType {
  fun giveHello(): String = "Hello!"
}

class Polite: MyType {
  // Does not override giveHello()
}

class Rude: MyType {
  override fun giveHello(): String = "I don't like you"
}
I get access to the
giveHello
method using reflection like this:
Copy code
val methodOfPolite = Polite::class.java.getDeclaredMethod("giveHello")
val methodOfRude = Rude::class.java.getDeclaredMethod("giveHello")
There's one weird thing here. The polite class does not override the
giveHello
method, but the
declaringClass
property of this method object still points to the class Polite. So is there a way I can check whether the class actually did override the default interface method or not? My use case looks something like this (assuming we can get the behaviour I'm asking for in a property called
isOverriden
):
Copy code
if (methodOfPolite.isOverriden) {
  // do something
} else {
  // do something else
}
Here's a link to the question on StackOverflow: https://stackoverflow.com/questions/58047229/how-to-check-if-a-class-has-overriden-a-default-method-from-an-interface-using-r/58047393
k
I think what's going on is that Kotlin default functions aren't actual JVM/Java default functions for 1.6 compatibility reasons. Every class that doesn't override a default function still overrides it but just calls the default implementation that's actually a static function somewhere.
So once you go
::class.java
there is no way to recover that information.
This expression does what you want:
Copy code
instance::class.memberFunctions.first { it.name == "giveHello" } in instance::class.declaredFunctions
1
Returns true if overridden.
h
Thanks, this works like a charm. Would you mind posting this answer to the StackOverflow link so that I can credit you with the answer?
k
Will do!
Done, I elaborated a bit more on how the code is compiled because I think it's interesting 🙂. https://stackoverflow.com/a/58047891/5517612
h
Thank you. Appreciate your effort!