【问题标题】:How do I constrain a class to implement a particular static method?如何约束一个类来实现一个特定的静态方法?
【发布时间】:2018-09-17 12:35:49
【问题描述】:

我在 Kafka 应用程序中使用了以下类:

public abstract class SerdeEnabled< Tse > {
    abstract public Serde< Tse > getSerde();
}

public class SerdeUsing< Tsu extends SerdeEnabled > {
    public void method() {
        Tsu tsu = new Tsu();  // Compile Error: cannot instantiate the type Tsu
        Serde< Tsu > serde = tsu.getSerde();
    }
}

如前所述,这不会编译。现在,getSerde() 方法不依赖于 其各自类的实例数据,实际上可以是static,除了 事实上,Java 不允许在抽象类(或接口)中使用静态方法。

我想我可以通过让SerdeUsing.method 获取一个 Tsu 实例来强制它工作, 然后用它来调用getSerde,但这看起来很难看。

关于如何获得预期效果的任何建议?

【问题讨论】:

    标签: java parameterized-types


    【解决方案1】:
    • java 8 允许在接口中使用静态方法
    • 您不能在 Tsu 上调用构造函数,因为它是类型参数。

    因此可以将 getSerde() 方法作为静态方法提取到接口中,并使 SerdeEnabled 实现该接口。

    【讨论】:

    • 谢谢。但是,我仍然卡住了,因为接口不允许我定义静态方法static Serde&lt; Tsu &gt; getSerde(...),给我一个类似的错误,因为Tsu 是接口的类型参数。有什么解决方法吗?
    • 静态 Serde getSerde() { ..}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 2015-09-13
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    相关资源
    最近更新 更多