Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What workaround to pass an instance variable to the super constructor?

Ok, so this is not allowed:

public class ServiceError extends RuntimeException {

    private final UUID uuid = UUID.randomUUID();

    public ServiceError(...) {
        super("{" + uuid.toString() + "} " + ...); // error on reference to uuid
    }

But how can I do what I want? There is no Exception.setMessage, so I can't change the message after the super constructor has been completed, I need to pass the UUID in the constructor.

like image 751
Bart van Heukelom Avatar asked Dec 22 '22 09:12

Bart van Heukelom


1 Answers

I would do this:

public class ServiceError extends RuntimeException {

    private final UUID uuid;

    public ServiceError() {
        this(UUID.randomUUID());
    }

    private ServiceError(UUID uuid) {
        super("{" + uuid.toString() + "} " + ...);
        this.uuid = uuid;
    }
}

Basically this is just a matter of changing where the UUID.randomUUID() call is made, and using a constructor parameter both to construct the superconstructor argument and to save the value to the field afterwards.

like image 157
Jon Skeet Avatar answered Apr 27 '23 22:04

Jon Skeet