簡體   English   中英

如何獲得每個類擴展的唯一 ID?

[英]How do I get an unique ID per class extention?

我有一個包含許多擴展子類的類:

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

我想要做的是一種簡單而輕松的方式來了解Mother類的兩個實例是否具有相同的實現:

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。

我的問題是:有沒有辦法在每次創建新擴展時自動給出不同的 ID,或者我必須自己做,在每個構造函數類中給出不同的編號?

如果沒有,有沒有更簡單的方法來完成我想要做的事情?

如果您只對 ID 樣式的解決方案感興趣...請嘗試使用以下機制:

在你的Mother類中聲明protected static int childClassesNumber; . 它將存儲加載的所有唯一子項的數量:

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();
  }
}

然后,為了確保每個孩子都獲得唯一的 ID,您應該在每個孩子中使用這樣的東西(這並不好):

class ChildOne extends Mother {
  public static final int ID;

  static {
    ID = ++Mother.childClassesNumber;
  }

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

ID只會在類加載階段給出(只有一次)

和(例如) 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()));

得到:

真的

錯誤的

這種機制有一個巨大的缺點——你應該把static初始化放在每個孩子中。 樣板代碼等等......所以我建議你使用@Ash解決方案)

看看java.util.UUID類及其靜態工廠方法public static UUID nameUUIDFromBytes(byte[] name) 這就是你要找的嗎?

不會

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

做這份工作嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM