Pitel
Pitel

Reputation: 5393

How to override private method

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?

Upvotes: 1

Views: 4438

Answers (2)

TheOperator
TheOperator

Reputation: 6476

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.

Upvotes: 5

PandarkMeow
PandarkMeow

Reputation: 11

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.

Upvotes: 1

Related Questions