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

Viewed 240

This is my function that decodes a JWT Object to String:

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();
}

SonarCloud detect a code smell when I convert base64Url.decode(base64EncodedBody), that is a byte[], on a String. This is the issue:

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.

How can I resolve this code smell?

1 Answers
Related