Java 中的静态方法和接口

Static methods and interfaces in Java

我有一个 UserEntity class 实现了 IUserEntity 接口。

UserEntityclass我有一张静态图:

private static Map<IUserEntity.IIdentifiable, IUserEntity> staticUserEntityMap = new HashMap<>();

IUserEntity接口中我想写一个这样的方法:

public Collection<IUserEntity>      getUsers();

并且在 class 中:

public static Collection<IUserEntity> getUsers(){
    return staticUserEntityMap.values();
}

但是我无法在接口中声明静态方法,也无法在 UserEntity class 中更改方法签名。

我该怎么做?

您可以创建抽象的 SkeletonUserEntity(或 AbstractUserEntity)class,您可以在其中定义此 getUser 方法和所有其他通用方法。所有 classes 都必须实现您从 SkeletonUserEntity

扩展的 IUserEntity

在 Java8 中,您可以在界面中使用默认实现,但我相信这不会解决您的问题。您可以创建一个单独的静态方法并在 getUsers 实现中使用 class 名称调用它,而不是更改方法签名。例如

创建新方法:

public static Collection<IUserEntity> getUsersStatic() {
   return staticUserEntityMap.values();
}

getUsers 调用此方法:

public Collection<IUserEntity>      getUsers() {
  return UserEntity.getUsersStatic();
}

我建议你参考 this question, and the docs:

In addition to default methods, you can define static methods in interfaces. (A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.) This makes it easier for you to organize helper methods in your libraries; you can keep static methods specific to an interface in the same interface rather than in a separate class.

但是,您也可以在接口中实现该字段,因为这将允许您实现简单的静态方法。缺点是地图会变成 public。它看起来像这样:

public interface  IUserEntity {
// ...

 static Map<IUserEntity.IIdentifiable, IUserEntity> staticUserEntityMap = new HashMap<>();

 static Collection<IUserEntity> getUsers(){
   return staticUserEntityMap.values();
 }
}