Search code examples
javaandroidkotlinreflectioninvoke

Getting *NoSuchMethodException* when method definitely is part of the class


I have the following class:

class CountryDataItem (
    id: Long?, 
    private val countryName :String?, 
    private var countryFlagUrl : String?,
    var gameCount : Int,  
    var liveCount:Int
) : BaseDataItem(id) {
    
    companion object {
        
        fun onCreateViewHolder(
            parent: ViewGroup,
            onRecyclerItemClickListener: OnRecyclerItemClickListener?
        ): RecyclerView.ViewHolder {
            val view: View =
                LayoutInflater.from(parent.context).inflate(R.layout.country_item, parent, false);
        }
    }
}

But when running:

someKClass.java.getMethod(
    "onCreateViewHolder",
    parent.javaClass,
    onRecyclerItemClickListenerRef.get()?.javaClass
)

I'm getting the exception. Can't understand why I even used the method : getMethods to get a list with the names of all the methods in the class, and the method exist. It means i'm sending a wrong parameter (but cannot figure out what is wrong) Attachment List:

enter image description here

Additional Info: The second argument i'm sending to getMethod is a WeakReference that conceal inside him a instance that is from type AllScoresFragment and also implements the interface OnRecyclerItemClickListener, but when i'm running the getMethod method with :

onRecyclerItemClickListenerRef.get()?.javaClass

, the result is AllScoresFragment type and not OnRecyclerItemClickListener type. Therefore he can't find the method and throws an exception. Trying to cast the object before sending it: val castedVariable = onRecyclerItemClickListenerRef.get() as? OnRecyclerItemClickListener

and then sending it as:

castedVariable.javaClass

doesn't help. Maybe someone can give me an idea how to overcome the problem?


Solution

  • Creating a companion object in a class Kotlin is equivalent to creating a static final class within a class in Java. So, the method defined in the companion object is not equivalent to a static method within a class in Java and cannot be accessed as you have tried to. Try this:

    import kotlin.reflect.full.companionObject
    
    someKClass.companionObject?.java?.getMethod(
        "onCreateViewHolder", 
        ViewGroup::class.java,
        OnRecyclerItemClickListener::class.java
    )
    

    If the import is not found add the kotlin-reflect library.

    implementation "org.jetbrains.kotlin:kotlin-reflect:1.4.20"