这是我将 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)
(即 byte[]
)时,SonarCloud 检测到代码味道。
这就是问题所在:
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
关于java - 当我使用 String 构造函数将 byte[] 转换为 String 时,SonarCloud 代码有异味,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65738248/