要自动生成序列化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在对象的生命周期内是唯一的。