Question about generics. Having this code: ```// ...
# stdlib
g
Question about generics. Having this code:
Copy code
// all T - java classes implementing ViewDataBinding, each providing a static `bind` method
// ViewDataBinding - a Java abstract class (with no declaration of `bind`)

interface BindingAware<T : ViewDataBinding> {
    var f: T

    fun bind(v: View) {
        // f = T.bind(a)  // <= how to call static method provided by class behind T?
    }
}
How to call static method of T, having only T?
r
implementing
ViewDataBinding
, each providing a static
bind
method
Unfortunately, that static method is not part of the interface definition, so there's no way for the compiler to resolve.
There's no way (that I'm aware of) to provide a generic
T
with any knowledge of the associated class statics. If all subclasses are known, you could use a lookup table, otherwise you'll likely need some reflection magic (or pass a reference to the static method in as a member of any implementation of
BindingAware
, but that seems to defeat the purpose).
g
no, all subclasses are not known tbh I made a simple solution using the reflection
Copy code
interface ViewBindingAware<T : ViewDataBinding> {
    var b: T
}

inline fun <reified T : ViewDataBinding> ViewBindingAware<T>.bindView(v: View): T {
    val bindMethod = T::class.java.getMethod("bind", View::class.java)
    b = bindMethod.invoke(null, v) as T
    return b
}
and it works but I don't like too much reflection-based solutions and I left it on a side for now