dimanche 22 septembre 2019

How to check if a class has overriden a default method from an interface using Reflection in Kotlin or Java?

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.

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:

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 of this method object still points to 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):

if (methodOfPolite.isOverriden) {
  // do something
} else {
  // do something else
}





Aucun commentaire:

Enregistrer un commentaire