当我使用 String 构造函数将 byte[] 转换为 String 时,SonarCloud 代码有异味

SonarCloud code smell when I convert byte[] to String with String constructor

这是我将 JWT 对象解码为字符串的函数:

protected String decodeJWT(String idToken){

    String[] splitString = idToken.split("\.");
    String base64EncodedBody = splitString[1];
    
    Base64 base64Url = new Base64(true);
    String idTokenString = new String(base64Url.decode(base64EncodedBody));
    StringBuilder sub = new StringBuilder();
    
    int indexStart = idTokenString.indexOf("\"sub\":\"") + 7;
    char c;
    while((c = idTokenString.charAt(indexStart)) != '\"') {
        indexStart++;
        sub.append(c);
    }
    
    return sub.toString();
}

当我在 String 上转换 base64Url.decode(base64EncodedBody) 时,SonarCloud 检测到代码味道,即 byte[]。 这是问题:

Constructors should not be used to instantiate "String", "BigInteger", "BigDecimal" and primitive-wrapper classes.

Constructors for String, BigInteger, BigDecimal and the objects used to wrap primitives should never be used. Doing so is less clear and uses more memory than simply using the desired value in the case of strings, and using valueOf for everything else.

我该如何解决这种代码异味?

使用这个构造函数

String(byte bytes[], Charset charset) 改为构造函数

因此代码可以改成

String s = new String(base64Url.decode(base64EncodedBody), StandardCharsets.UTF_8);

参考https://gazelle.ihe.net/sonar/coding_rules?open=squid%3AS1943&rule_key=squid%3AS1943

String constructors with a byte[] argument but no Charset argument is a minor code smell