Java Record "toString()" mask sensitive fields
Asked Answered
L

1

7

Is there any way to mask sensitive fields on the automatically generated "toString()" method in Java Records without overriding it? (i.e. Annotations)

i.e.

public record SomeRecord(..., String apiKey, String password, ...) { }

Please no "Use Lombok!" answers :)

Lardon answered 15/3 at 0:53 Comment(6)
The answer is no, there isn't.Hooch
What I feared...but seems like it would be a good addition :)Lardon
An addition at the language level? When overriding toString in the very rare event you need to do this is so easy?Danais
yes @Danais that wasn't really serious, but I saw Lombok had a feature-request for this...which ultimately got rejected :)Lardon
As suggestion, try to use public class ReflectionToStringBuilder.Stronski
@FranciscoValadares yes I could do that or just override toString() which is probably what I will end up doing, but the question was if I can avoid that via some trick and reduce boilerplateLardon
T
6

I think you can wrap the sensitive info by the object:

record SensitiveInfo(String info) {
   public String toString() {
      // add your masking func here
    }
   // other necessary methods to use with info field
}

So in your SomeRecord:

record SomeRecord(..., SensitiveInfo apiKey, SensitiveInfo password)
Turkmen answered 15/3 at 1:0 Comment(3)
The question asks for a way of doing this without overriding toStringDanais
I think still a valid response because this solution doesn't override toString in the record. :) Not necessarily always Strings but the SensitiveInfo could just as easily uses Object#toString(). In my particular situation I am using the records for Spring @ConfigurationProperties so this would be overly complex for the automatic conversions :) but I get what you were thinking.Lardon
@Lardon fair enough, I missed that.Danais

© 2022 - 2024 — McMap. All rights reserved.