在 Eclipse IDE(核心 Java)中调试时,检查对象显示后跟一个 id,例如:myObject=MyClass (id=123)
为了检测意外的对象更改,记录任何 OID 也会很有帮助。知道如何编写返回对象特定唯一 ID 的 getOid() 方法吗?它不需要是可序列化的,它只是在一次运行中使用。与 hashCode() 相比,OID 必须是唯一的。此 getOid() 可能返回 int、long、String 或任何可打印的内容。先感谢您
I believe System.identityHashCode(Object x) is what you are looking for. As given by the javadoc, It prints out the same value as would be printed by the objects default hashCode(). This should be unique, as it is often the memory address for the object. In this case you could use the default hashCode() as well.
You could also override the hashCode() method using java.util.Objects.hash(Object... values) and passing in the fields of your object. This will verify for you that the internals of your object aren't changing.
However, are you trying to track the same internal ID as defined by Eclipse? I'm not positive, but I suspect that is assigned by the Eclipse debugger internally and is unavailable for you.
没有 OIDGenerator 构造函数的更简单的版本:
公共类 OIDGenerator {
private static long sOID = 0;
public static long longNext() {
return ++sOID;
}
public static String next() {
return new StringBuffer( "@").append( String.valueOf( longNext())).toString();
}
}
但请记住,由于静态变量,两个版本都不能在服务器集群中使用。
好的,我通过所有构造函数中使用的序列生成器“OIDGenerator”解决了它:
公共类 OIDGenerator {
private static OIDGenerator mOIDGen;
private static long mOID;
/**
* Singleton Constructor
*/
private OIDGenerator() {
mOID = 0;
}
public static long longNext() {
if( mOIDGen == null) {
mOIDGen = new OIDGenerator(); // => init 0
}
return ++mOID;
}
public static String next() {
return new StringBuffer( "@").append( String.valueOf( longNext())).toString();
}
}
所有类中的成员变量:
private final transient String mOID;
在他们的构造函数中:
mOID = OIDGenerator.next();
提供方法:
@Override
public String getOID() {
return mOID;
}