默认接口方法的辅助函数
helper function for default interface method
我需要合并一些辅助方法来辅助 Java 8 上接口的默认方法 - 以更好地组织代码。
所以唯一可用的选择似乎是用 'static'
来限定它们 - 从而让它们暴露在外面。
有没有更好的方法来实现这一目标 - 迁移到 Java 9 不是一种选择。
如果您可以选择升级到更新的版本,您实际上可以在界面中使用 private
方法
在 Java 9 和更新版本中,接口允许私有(非抽象)方法。见 JSL 9.4:
A method in the body of an interface may be declared public
or private
(§6.6). If no access modifier is given, the method is implicitly public
...
并且这些私有方法也可能是静态的(相同来源):
...It is permitted for an interface method declaration to contain both private and static.
如果你必须留在 Java 8,你可以使用 package-private 类 和方法(是的,这不是类型私有的,但 package-private 是更好的选择)
public interface Interface {
default void doSomething() {
InterfaceHelper.doSomething();
}
}
class InterfaceHelper {
static void doSomething() { //package-private class and method
}
}
我需要合并一些辅助方法来辅助 Java 8 上接口的默认方法 - 以更好地组织代码。
所以唯一可用的选择似乎是用 'static'
来限定它们 - 从而让它们暴露在外面。
有没有更好的方法来实现这一目标 - 迁移到 Java 9 不是一种选择。
如果您可以选择升级到更新的版本,您实际上可以在界面中使用 private
方法
在 Java 9 和更新版本中,接口允许私有(非抽象)方法。见 JSL 9.4:
A method in the body of an interface may be declared
public
orprivate
(§6.6). If no access modifier is given, the method is implicitlypublic
...
并且这些私有方法也可能是静态的(相同来源):
...It is permitted for an interface method declaration to contain both private and static.
如果你必须留在 Java 8,你可以使用 package-private 类 和方法(是的,这不是类型私有的,但 package-private 是更好的选择)
public interface Interface {
default void doSomething() {
InterfaceHelper.doSomething();
}
}
class InterfaceHelper {
static void doSomething() { //package-private class and method
}
}