Learn Pain Less

HomeOur TeamContact
Kotlin
How to access Java private field in Kotlin extension function
Pawneshwer Gupta
Pawneshwer Gupta
March 08, 2017
1 min

Table Of Contents

01
How to access Java private field in Kotlin extension function
02
So here is fix to resolve this problem
How to access Java private field in Kotlin extension function

How to access Java private field in Kotlin extension function

If I’d like to access Java’s private field when using Kotlin extension function.

Suppose I have a Java class ABC. ABC has only one private field mPrivateField. I’d like to write an extension function in Kotlin which uses that field for whatever reason.

public class ABC {
private int mPrivateField;
}

the Kotlin function would be:

private fun ABC.testExtFunc() {
val canIAccess = this.mPrivateField;
}

the error I’m getting is:

Cannot access 'mPrivateField': It is private in 'ABC'

So here is fix to resolve this problem

First of all we will pick a Field from Java class then we will enable that field to make it accessible from Kotlin code.

Example:

val field = ABC::class.java.getDeclaredField("mPrivateField")
field.isAccessible = true

Now we can read field value as Int using Field#getInt function from instance of our ABC class (declaring class).

Example:

val it: ABC = TODO()
val value = field.getInt(it)

Now our extension method in Kotlin will look like this:

private inline fun ABC.testExtFunc():Int {
return javaClass.getDeclaredField("mPrivateField").let {
it.isAccessible = true
val value = it.getInt(this)
//todo
return@let value;
}
}

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Tags

extension functionjavaprivate field

Share


Pawneshwer Gupta

Pawneshwer Gupta

Software Developer

Pawneshwer Gupta works as a software engineer who is enthusiastic in creating efficient and innovative software solutions.

Expertise

Python
Flutter
Laravel
NodeJS

Social Media

Related Posts

What is an Object in java programming
Java
What is an Object in java programming
February 06, 2015
1 min
Learn Pain Less  © 2024, All Rights Reserved.
Crafted with by Prolong Services

Quick Links

Advertise with usAbout UsContact Us

Social Media