master
面包骑士 2024-08-20 11:29:53 +08:00
parent 4bb111bb9a
commit 578b210800
1 changed files with 19 additions and 14 deletions

View File

@ -700,27 +700,32 @@ public class Convert {
* @return * @return
*/ */
public static String str(Object obj, Charset charset) { public static String str(Object obj, Charset charset) {
if (null == obj) { if (obj == null) {
return null; return null;
} }
if (obj instanceof String) { if (obj instanceof String) {
// 如果已经是String则直接返回
return (String) obj; return (String) obj;
} else if (obj instanceof byte[] || obj instanceof Byte[]) { } else if (obj instanceof byte[]) {
if (obj instanceof byte[]) { // 如果是byte[]则使用charset进行编码转换
return str((byte[]) obj, charset); return new String((byte[]) obj, charset);
} else { } else if (obj instanceof Byte[]) {
// 如果是Byte[]先转换为byte[],再进行编码转换
Byte[] bytes = (Byte[]) obj; Byte[] bytes = (Byte[]) obj;
int length = bytes.length; byte[] dest = new byte[bytes.length];
byte[] dest = new byte[length]; for (int i = 0; i < bytes.length; i++) {
for (int i = 0 ; i < length ; i++) { dest[i] = bytes[i].byteValue(); // 使用byteValue()来避免自动拆箱
dest[i] = bytes[i];
}
return str(dest, charset);
} }
return new String(dest, charset);
} else if (obj instanceof ByteBuffer) { } else if (obj instanceof ByteBuffer) {
return str((ByteBuffer) obj, charset); // 如果是ByteBuffer则根据position和limit进行转换
ByteBuffer buffer = (ByteBuffer) obj;
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes); // 从buffer中读取到字节数组
return new String(bytes, charset);
} }
// 如果都不是则调用对象的toString方法这里不使用charset
return obj.toString(); return obj.toString();
} }