This may be a bit difficult to describe, so I'll try to give a concrete example of what I'm trying to do.

假设我们有一个门面接口和类(Java),如下所示:

interface FacadeInterface<T> {
    void method(String from, String via);
}

class Facade<T> implements FacadeInterface<T> {
    private Class<T> mClazz;

    public Facade(Class<T> clazz) {
        mClazz = clazz;
    }

    @Override
    public void method(String from, String via) {
        System.out.println("Method called from " + from + " via " + via);
    }
}

在我的应用程序中,我需要有多个单例来保存外观的一个实例.真正的外观有额外的设置/配置参数,但是这些参数在这里是不相关的.

在我开始使用kotlin之前,我会有一个包含外观的静电实例的类(不是真正的单一实例,但在我的例子中,它有类似的用途),它将调用代理到外观,如下所示:

public class Singleton {
    private static final FacadeInterface<String> sFacade = new Facade<>(String.class);

    private Singleton() {
    }

    public static void method(String from, String via) {
        sFacade.method(from, via);
    }
}

Now, with Kotlin we have class delegates which allow me to write something like this:

object SingletonKt : FacadeInterface<String> by Facade(String::class.java)

这很棒-没有更多的样板,我可以调用SingletonKtfrom Kotlin类,就像我调用Java Singleton的方式一样:

Singleton.method("Kotlin", "Singleton")
SingletonKt.method("Kotlin", "SingletonKt")

但是,当我使用SingletonKtfrom Java时,出现了一个小问题.那么我必须指定INSTANCE:

Singleton.method("Java", "Singleton");
SingletonKt.INSTANCE.method("Java", "SingletonKt");

我知道@JvmStatic注释,但是我可以将它放在SingletonKt文件中而不会导致编译错误的唯一位置就在FacadeInterface之前,它似乎没有起到作用.

有没有一种方法可以设置这个类委托,这样我就可以从Java调用它,就好像它是一个静态方法一样,而不需要引入为SingletonKt创建代理方法的样板文件(这会 destruct 类委托的用途)?

推荐答案

It's sadly not possilble!

The Kotlin Delegation is a nice way to reduce boilerplate code. But it comes with the inability to actually access the delegate within the class body.

The second issue you're facing regarding @JvmStatic is actually more drastic to your cause than the first and also applies to you when implementing the delegation manually:

Override members cannot be '@JvmStatic' in object

因此,您可以将其委托给对象上的staticMethod(),而不是仅通过INSTANCE公开method().这仍然与您的意图不同,但已接近您的意图.

object SingletonKt : FacadeInterface<String> by Facade(String::class.java)
    @JvmStatic fun staticMethod(from: String, via: String) = method(from, to)
}

Kotlin相关问答推荐

文本正在被切断在200%的屏幕比例在Jetpack Compose

Kotlin和JavaFX:绑定行为奇怪

如何避免使用公共类实现内部接口

在Jetpack Compose中创建波浪式文本动画:顺序中断问题

Kotlin 中的 maxOf() 和 max() 方法有什么区别?

如何将光标从一个文本字段传递到 Jetpack Compose 中的其他文本字段?

为什么 Kotlin 在 sumOf 函数 lambda 中默认不将数字视为Int?

Swift vs Kotlin 在排序数组上的表现

基类中的 ViewModelProviders.get(...)

为什么 Kotlin 需要函数引用语法?

对列表中数字的子集求和

是否可以在 kotlin 中嵌套数据类?

在构造函数中仅注入某些参数

Kotlin 单元测试 - 如何模拟 Companion 对象的组件?

Android:在 DAO 中使用 Room 数据库和 LiveData 架构

Kotlin - 来自 KType 的 KClass<*>

ObserveForver是否了解生命周期?

如何在Kotlin中创建无限长的序列

如何为 Java 调用者声明返回类型为void的 Kotlin Lambda?

如何使用mockk库模拟android上下文