好的,所以这是不允许的:
public class ServiceError extends RuntimeException {
private final UUID uuid = UUID.randomUUID();
public ServiceError(...) {
super("{" + uuid.toString() + "} " + ...); // error on reference to uuid
}
Run Code Online (Sandbox Code Playgroud)
但我怎么能做我想要的呢?没有Exception.setMessage,所以超级构造已经完成后,我无法改变的消息,我需要通过UUID在构造函数中.
我会这样做:
public class ServiceError extends RuntimeException {
private final UUID uuid;
public ServiceError() {
this(UUID.randomUUID());
}
private ServiceError(UUID uuid) {
super("{" + uuid.toString() + "} " + ...);
this.uuid = uuid;
}
}
Run Code Online (Sandbox Code Playgroud)
基本上这只是改变UUID.randomUUID()调用位置的问题,并使用构造函数参数构造超构造参数并在之后将值保存到字段中.