java - java接口(interface)中的静态方法

标签 java interface static-methods

据我所知,您不能在接口(interface)主体中声明静态方法。然而,无意中我在 http://docs.oracle.com/ 上发现了一段奇怪的代码地点。这是 link

就是

public interface TimeClient 
{
void setTime(int hour, int minute, int second);
void setDate(int day, int month, int year);
void setDateAndTime(int day, int month, int year,
                           int hour, int minute, int second);
LocalDateTime getLocalDateTime();

static ZoneId getZoneId (String zoneString) {
    try {
        return ZoneId.of(zoneString);
    } catch (DateTimeException e) {
        System.err.println("Invalid time zone: " + zoneString +
            "; using default time zone instead.");
        return ZoneId.systemDefault();
    }
}

default ZonedDateTime getZonedDateTime(String zoneString) {
    return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
    }
}

这个接口(interface)有一个static方法getZoneId

我迷路了...谁能解释一下

最佳答案

在这里您见证了 Java 8 中的两个新特性:

  • 接口(interface)中的静态方法,
  • 虚拟扩展方法。

在您提供的代码示例中,getZoneId() 说明了第一个新颖之处,.getZoneDateTime() 说明了第二个。

特别是第二个是允许 Collection 接口(interface)使用 .stream() 等补充方法进行扩展,例如,没有 打破向后兼容性。参见 here举例说明。

第一个允许避免编写“方法包”类,这些类通常只存在于接口(interface)上提供实用静态方法。一个这样的例子是 Guava's Functions class (不要与 Java 8 的 Function 混合使用,它基本上是从 Guava 窃取的,还有 Predicate 和其他一些)

关于java - java接口(interface)中的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23148471/

相关文章:

java - 如何使用for循环在java中创建一个后向三角形

Java 泛型 : why I cannot pass the Bounded Type Parameters actual in one method to the other method?

java - 我应该创建静态方法还是抽象父类(super class)

python - staticmethod 和 classmethod 装饰器可以用纯 Python 实现吗?

java - 使用自定义类加载器加载静态方法

java - POI 将 excel 字符串读取为数字

java - JSF 和表达式语言 : Bind property only when it exists

c++ - 使用文本调整 QToolButton 的大小

pointers - 如何在类型断言后调用带有指针接收器的方法?

java - 将没有字段的抽象类转换为接口(interface)(Java,Sonar 规则 s1610)