如何为每个 class 分机获取唯一 ID?

How do I get an unique ID per class extention?

我有一个 class 有许多扩展子 classes:

class FirstImplementation extends Mother { [...]
class SecondImplementation extends Mother { [...]
class ThirdImplementation extends Mother { [...]

我想做的是一种简单明了的方法来了解 Mother class 的两个实例是否具有相同的实现:

Mother   a = new FirstImplementation();
Mother   b = new SecondImplementation();
Mother   c = new FirstImplementation();

a.sameKindOf(b); // return false;
a.sameKindOf(c); // return true;

我的想法是在每个Mother实例中设置一个整数ID字段,然后在sameKindOf函数中比较它:

public class Mother {
    private final int ID;

    protected Mother(int ID) {
        this.ID = ID;
    }

    public int getID() {
        return this.ID;
    }

    public boolean sameKindOf(Mother other) {
        return this.ID == other.getID();
    }
}

Mother 的每个扩展都应使用精确的 ID 调用 Mother 的构造函数。

我的问题是:有没有办法在我每次创建新扩展时自动提供不同的 ID,或者我必须自己做,在每个构造函数中提供不同的编号 class?

如果没有,是否有更简单的方法来完成我想做的事情?

看看 java.util.UUID class 及其静态工厂方法 public static UUID nameUUIDFromBytes(byte[] name)。这就是您要找的吗?

不会

public boolean sameKindOf(Mother other) {
    return this.getClass().equals(other.getClass());
}

做作业?

如果您只对ID-style解决方案感兴趣...尝试使用以下机制:

在您的 Mother class 中声明 protected static int childClassesNumber;。它将存储已加载的所有唯一 child 的数量:

class Mother {
  protected static int childClassesNumber = 0;
  private final int ID;

  protected Mother(int ID) {
    this.ID = ID;
  }

  public int getID() {
    return this.ID;
  }

  public boolean sameKindOf(Mother other) {
    return this.ID == other.getID();
  }
}

然后,为了确保每个 child 获得唯一的 ID,您应该在每个 child 中使用类似这样的东西(这并不好):

class ChildOne extends Mother {
  public static final int ID;

  static {
    ID = ++Mother.childClassesNumber;
  }

  public ChildOne() {
    super(ID);
  }
}

ID只会在class加载阶段给出(只有一次)

和(例如)ChildTwo

class ChildTwo extends Mother {
  public static final int ID;

  static {
    ID = ++Mother.childClassesNumber;
  }

  public ChildTwo() {
    super(ID);
  }
}

之后,下面的代码

System.out.println(new ChildOne().sameKindOf(new ChildOne()));
System.out.println(new ChildOne().sameKindOf(new ChildTwo()));

得到:

true

false

这种机制有一个很大的缺点——你应该把 static 初始化放在每个 child 中。样板代码等等......所以我建议你使用@Ash 解决方案)