不再使用反射调用 Java 9~11 中引入的 API (#4114)

This commit is contained in:
Glavo
2025-07-25 17:02:37 +08:00
committed by GitHub
parent 24d3bbf4fe
commit 96f68e1017
23 changed files with 64 additions and 354 deletions

View File

@@ -246,7 +246,7 @@ public class DefaultGameRepository implements GameRepository {
try {
versions.remove(id);
if (FileUtils.isMovingToTrashSupported() && FileUtils.moveToTrash(removedFile)) {
if (FileUtils.moveToTrash(removedFile)) {
return true;
}

View File

@@ -45,7 +45,7 @@ public final class StringUtils {
}
public static boolean isBlank(String str) {
return str == null || str.trim().isEmpty();
return str == null || str.isBlank();
}
public static boolean isNotBlank(String str) {

View File

@@ -24,14 +24,12 @@ import org.jackhuang.hmcl.util.platform.OperatingSystem;
import java.io.File;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;
import java.nio.file.*;
import java.nio.file.spi.FileSystemProvider;
import java.util.*;
import java.util.zip.ZipError;
import java.util.zip.ZipException;
/**
@@ -59,7 +57,7 @@ public final class CompressingUtils {
}
}
public static boolean testEncoding(ZipArchiveReader zipFile, Charset encoding) throws IOException {
public static boolean testEncoding(ZipArchiveReader zipFile, Charset encoding) {
CharsetDecoder cd = newCharsetDecoder(encoding);
CharBuffer cb = CharBuffer.allocate(32);
@@ -71,7 +69,7 @@ public final class CompressingUtils {
int clen = (int)(ba.length * cd.maxCharsPerByte());
if (clen == 0) continue;
if (clen <= cb.capacity())
((Buffer) cb).clear(); // cast to prevent "java.lang.NoSuchMethodError: java.nio.CharBuffer.clear()Ljava/nio/CharBuffer;" when compiling with Java 9+
cb.clear();
else
cb = CharBuffer.allocate(clen);
@@ -212,9 +210,6 @@ public final class CompressingUtils {
throw new FileSystemNotFoundException("Module jdk.zipfs does not exist");
return ZIPFS_PROVIDER.newFileSystem(zipFile, env);
} catch (ZipError error) {
// Since Java 8 throws ZipError stupidly
throw new ZipException(error.getMessage());
} catch (UnsupportedOperationException ex) {
throw new ZipException("Not a zip file");
} catch (FileSystemNotFoundException ex) {

View File

@@ -25,7 +25,6 @@ import org.jackhuang.hmcl.util.function.ExceptionalConsumer;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
import java.io.*;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
@@ -328,18 +327,9 @@ public final class FileUtils {
/**
* Move file to trash.
* <p>
* This method is only implemented in Java 9. Please check we are using Java 9 by invoking isMovingToTrashSupported.
* Example:
* <pre>{@code
* if (FileUtils.isMovingToTrashSupported()) {
* FileUtils.moveToTrash(file);
* }
* }</pre>
*
* @param file the file being moved to trash.
* @return false if moveToTrash does not exist, or platform does not support Desktop.Action.MOVE_TO_TRASH
* @see FileUtils#isMovingToTrashSupported()
*/
public static boolean moveToTrash(File file) {
if (OperatingSystem.CURRENT_OS.isLinuxOrBSD() && hasKnownDesktop()) {
@@ -393,33 +383,12 @@ public final class FileUtils {
}
try {
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
Method moveToTrash = desktop.getClass().getMethod("moveToTrash", File.class);
moveToTrash.invoke(desktop, file);
return true;
return java.awt.Desktop.getDesktop().moveToTrash(file);
} catch (Exception e) {
return false;
}
}
/**
* Check if {@code java.awt.Desktop.moveToTrash} exists.
*
* @return true if the method exists.
*/
public static boolean isMovingToTrashSupported() {
if (OperatingSystem.CURRENT_OS.isLinuxOrBSD() && hasKnownDesktop()) {
return true;
}
try {
java.awt.Desktop.class.getMethod("moveToTrash", File.class);
return true;
} catch (ReflectiveOperationException e) {
return false;
}
}
public static void cleanDirectory(File directory)
throws IOException {
if (!directory.exists()) {

View File

@@ -78,7 +78,7 @@ public final class IOUtils {
public static String readFullyAsStringWithClosing(InputStream stream) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream(Math.max(stream.available(), 32));
copyTo(stream, result);
return result.toString("UTF-8");
return result.toString(UTF_8);
}
/**
@@ -101,11 +101,11 @@ public final class IOUtils {
}
public static String readFullyAsString(InputStream stream) throws IOException {
return readFully(stream).toString("UTF-8");
return readFully(stream).toString(UTF_8);
}
public static String readFullyAsString(InputStream stream, Charset charset) throws IOException {
return readFully(stream).toString(charset.name());
return readFully(stream).toString(charset);
}
public static void copyTo(InputStream src, OutputStream dest) throws IOException {

View File

@@ -294,7 +294,7 @@ public final class Logger {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
exportLogs(output);
return output.toString("UTF-8");
return output.toString(UTF_8);
} catch (IOException e) {
log(Level.WARNING, CLASS_NAME + ".getLogs", "Failed to export logs", e);
return "";

View File

@@ -17,14 +17,10 @@
*/
package org.jackhuang.hmcl.util.platform;
import org.jackhuang.hmcl.java.JavaRuntime;
import org.jackhuang.hmcl.launch.StreamPump;
import org.jackhuang.hmcl.util.Lang;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
@@ -84,47 +80,6 @@ public final class ManagedProcess {
return process;
}
/**
* The PID of the raw system process
*
* @throws UnsupportedOperationException if current Java environment is not supported.
* @return PID
*/
public long getPID() throws UnsupportedOperationException {
if (JavaRuntime.CURRENT_VERSION >= 9) {
// Method Process.pid() is provided (Java 9 or later). Invoke it to get the pid.
try {
return (long) MethodHandles.publicLookup()
.findVirtual(Process.class, "pid", MethodType.methodType(long.class))
.invokeExact(process);
} catch (Throwable e) {
throw new UnsupportedOperationException("Cannot get the pid", e);
}
} else {
// Method Process.pid() is not provided. (Java 8).
if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS) {
// On Windows, we can invoke method Process.pid() to get the pid.
// However, this method is supplied since Java 9.
// So, there is no ways to get the pid.
throw new UnsupportedOperationException("Cannot get the pid of a Process on Java 8 on Windows.");
} else if (OperatingSystem.CURRENT_OS == OperatingSystem.MACOS || OperatingSystem.CURRENT_OS.isLinuxOrBSD()) {
// On Linux or Mac, we can get field UnixProcess.pid field to get the pid.
// All the Java version is accepted.
// See https://github.com/openjdk/jdk/blob/jdk8-b120/jdk/src/solaris/classes/java/lang/UNIXProcess.java.linux
try {
Field pidField = process.getClass().getDeclaredField("pid");
pidField.setAccessible(true);
return pidField.getInt(process);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new UnsupportedOperationException("Cannot get the pid of a Process on Java 8 on macOS/Linux.", e);
}
} else {
// Unknown Operating System, no fallback available.
throw new UnsupportedOperationException(String.format("Cannot get the pid of a Process on Java 8 on Unknown Operating System (%s).", System.getProperty("os.name")));
}
}
}
/**
* The command line.
*

View File

@@ -17,7 +17,6 @@
*/
package org.jackhuang.hmcl.util.platform;
import org.jackhuang.hmcl.java.JavaRuntime;
import org.jackhuang.hmcl.task.Schedulers;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.function.ExceptionalFunction;
@@ -110,7 +109,7 @@ public final class SystemUtils {
}
public static boolean supportJVMAttachment() {
return JavaRuntime.CURRENT_VERSION >= 9 && Thread.currentThread().getContextClassLoader().getResource("com/sun/tools/attach/VirtualMachine.class") != null;
return Thread.currentThread().getContextClassLoader().getResource("com/sun/tools/attach/VirtualMachine.class") != null;
}
private static void onLogLine(String log) {