Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Java Immutables to generate toString() for Throwable classes

Is it possible to force Java Immutables annotation processing library to generate toString method for an abstract class which already inherits non-default toString() method?

For example:

@Value.Immutables
public abstract class MyRuntimeException extends RuntimeException {
    @Value.Default
    public abstract long timestamp();
    @Value.Redacted
    public abstract long secretTimestamp();
}

And result to be:

MyRuntimeException e = ImmutableMyRuntimeException.builder().timestamp(111)
                                              .secretTimestamp(222).build();
assert e.toString().contains("111");
assert !e.toString().contains("222");

RuntimeException inherits toString() from Throwables and what I have seen so far Immutables library skips generating toString() because of that.

like image 472
DaTval Avatar asked Jan 30 '26 16:01

DaTval


1 Answers

There is one such way. The trick is to declare abstract toString method signature in abstract value type.

@Value.Immutable
public abstract class MyRuntimeException extends RuntimeException {
    public abstract long timestamp();
    public abstract long secretTimestamp();
    @Override public abstract String toString(); //<-- forces toString impl
}
like image 197
Ievgen Lukash Avatar answered Feb 01 '26 06:02

Ievgen Lukash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!