简体   繁体   English

Kotlin将类型函数作为函数扩展来实现 - 可以从Java调用吗?

[英]Kotlin reified type function as function extension - Callable from Java?

I'm trying to use a function with reified type as extension function but I don't think that it's possible because after I checked the generated bytecode I have find that the method signature is private, any work around to make it public ? 我正在尝试使用具有reified类型的函数作为扩展函数,但我不认为这是可能的,因为在我检查生成的字节码后我发现方法签名是私有的,是否有任何解决方法使其公开?

CommonExtensions.kt CommonExtensions.kt

inline fun<reified T: Activity> Context.startActivity() {
    val intent = Intent(this, T:: class.java)
    startActivity(intent)
}

fun View.visible() {
    visibility = View.VISIBLE
}

Kotlin Bytecode : Kotlin字节码:

private final static startActivity(Landroid/content/Context;)V
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
   ...

Client Code : 客户代码:

Kotlin file Kotlin文件

override fun showMessageEmptyOfferFeeds() {
        mOfferFeedsWarning.visible() // "visible()" extension func RESOLVED
}

Java file Java文件

showProfileDetailsUi(){
   startActivity<DetailActivity>() //"startActivity()" extension func NOT RESOLVED
}

Yes you can use inline functions with reified types as extension functions. 是的,您可以使用带有reified类型的inline函数作为扩展函数。 It's made private so that Java code can't access it (btw this is not the case for "normal" inline functions). 它是private因此Java代码无法访问它(顺便说一下,这不是“普通” inline函数的情况)。 Such an inline function can be private for Kotlin because inline functions are copied to the place where they are invoked . 这样的inline函数可以是private ,因为内联函数被复制 他们调用的地方科特林

An example : 一个例子

inline fun <reified T : Activity> Activity.startActivity() {
    startActivity(Intent(this, T::class.java))
}

//usage

startActivity<DetailActivity>()

Read more about reified in another SO question, I answered: https://stackoverflow.com/a/45952201/8073652 阅读更多关于在另一个SO问题中的reified ,我回答: https//stackoverflow.com/a/45952201/8073652

Once again: You cannot use inline functions with reified typed from Java. 再次: 你不能使用inline函数用reified从Java类型。

inline reified functions 'disppear' after compilation, because reified types don't exist on the JVM. 编译后的inline reified reified函数'disppear',因为JVM上不存在reified类型。 It is a trick by the compiler. 这是编译器的一个技巧。

Probably the only reason the private function is there is to cause an error if someone tries to override it during runtime, since the reified function is completely inlined and cannot be overridden. 私有函数存在的唯一原因可能是,如果有人在运行时尝试覆盖它,则会导致错误,因为已知内联函数是完全内联的,无法覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM