有几种方法可以禁用非法访问警告,尽管我不建议您这样做。
1.简单的方法
由于警告已打印到默认错误流,因此您只需关闭此流并重定向
stderr到即可
stdout。
public static void disableWarning() { System.err.close(); System.setErr(System.out);}笔记:
- 这种方法合并了错误流和输出流。在某些情况下,这可能不是理想的。
- 您不能仅通过调用来重定向警告消息
System.setErr
,因为错误流的引用IllegalAccessLogger.warningStream
在JVM引导程序的早期就保存在字段中。
2.无需更改标准错误的复杂方法
一个好消息是,
sun.misc.Unsafe仍可以在JDK 9中访问它而不会发出警告。解决方案是在
IllegalAccessLoggerUnsafe
API的帮助下重置内部。
public static void disableWarning() { try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); Unsafe u = (Unsafe) theUnsafe.get(null); Class cls = Class.forName("jdk.internal.module.IllegalAccessLogger"); Field logger = cls.getDeclaredField("logger"); u.putObjectVolatile(cls, u.staticFieldOffset(logger), null); } catch (Exception e) { // ignore }}


