如何在Java中访问Kotlin伴侣对象? [英] How to access Kotlin companion object in Java?

查看:655
本文介绍了如何在Java中访问Kotlin伴侣对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Java类之一转换为Kotlin,然后将其转换为以下类.

I convert one of my Java class to Kotlin and the class as below.

class MainApplication : Application() {
    companion object {
        operator fun get(context: Context): MainApplication {
            return context.applicationContext as MainApplication
        }
    }
}

它具有静态功能get.

我仍然有Java函数可以访问它.

I still have a Java function accessing it.

MainApplication application = MainApplication.get(mContext);

MainApplication使用Java时很好.但是不是当Kotlin中的MainApplication出现上述代码错误

It was good when MainApplication is in Java. But not when MainApplication in Kotlin, the above code error

Error:(27, 54) error: cannot find symbol method get(Context)

如何在上面的Java代码中访问get?

How could I access get in my Java code above?

推荐答案

您可以添加

You can add @JvmStatic annotation to the method in companion object to make Kotlin generate a static method.

class MainApplication : Application() {
    companion object {
        @JvmStatic fun get(context: Context): MainApplication {
            return context.applicationContext as MainApplication
        }
    }
}

然后,您可以像转换为Kotlin之前那样从Java访问它:

you can then access it from Java like before converting to Kotlin:

MainApplication application = MainApplication.get(mContext);

我觉得有必要添加我最近学到的东西:@JvmStatic实际上并没有移动该方法的生成位置.除了伴随对象上的方法之外,它还通过为Java生成静态方法来复制.我个人认为这不是很好,它可能会因用例而产生某些影响,因此有些事情应该知道.

I feel obliged to add something I learned recently: @JvmStatic doesn't actually move where the method gets generated. It duplicates it, by generating a static method for Java in addition to the method on the companion object. Personally I think this isn't great and it can have some implications depending on a use case, so something worth knowing.

这篇关于如何在Java中访问Kotlin伴侣对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆