要自動生成序列化ID,可以考慮以下幾種方法:
import java.util.UUID;
public class MyClass {
private String id;
public MyClass() {
this.id = UUID.randomUUID().toString();
}
// Getters and setters
}
import java.util.concurrent.atomic.AtomicLong;
public class MyClass {
private static final AtomicLong idGenerator = new AtomicLong(0);
private long id;
public MyClass() {
this.id = idGenerator.incrementAndGet();
}
// Getters and setters
}
public class MyClass {
private long id;
public MyClass() {
this.id = System.currentTimeMillis();
}
// Getters and setters
}
無論使用哪種方法生成序列化ID,都需要保證生成的ID在對象的生命周期內是唯一的。