0

I am extending existing Java class which has some private method. And to achieve what I want, I have to to override this private method.

So I read something about Java reflection, and came out with the following:

class CustomSlider : Slider() {
    init {
        Slider::class.java.getDeclaredMethod("drawTrack", Canvas::class.java, Int::class.java, Int::class.java).isAccessible = true
    }

    override fun drawTrack(canvas: Canvas, width: Int, top: Int) {
    }
}

But on the override line, I'm getting an error that it's not possible.

So how can I do this?

Pitel
  • 5,334
  • 7
  • 45
  • 72

2 Answers2

4

It is not possible to override private methods, neither in Kotlin nor in Java.

Reflection does not help here. Private methods are dispatched statically, not dynamically -- that is, the correct implementation is chosen at compile time, not runtime.

See also:

To "achieve what you want", you should go another route -- if the API you use foresees extension, it will likely offer that in one way or another.

TheOperator
  • 5,936
  • 29
  • 42
1

I think you need to change "private" to "protected". Private methods is available inside the class while protected methods is available for the class and its children.