如何隐藏警告“非法反射访问"在没有JVM参数的Java 9中? [英] How to hide warning "Illegal reflective access" in java 9 without JVM argument?
问题描述
我刚刚尝试使用Java 9运行服务器,并收到下一条警告:
I just tried to run my server with Java 9 and got next warning:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by io.netty.util.internal.ReflectionUtil (file:/home/azureuser/server-0.28.0-SNAPSHOT.jar) to constructor java.nio.DirectByteBuffer(long,int)
WARNING: Please consider reporting this to the maintainers of io.netty.util.internal.ReflectionUtil
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
我想隐藏此警告,而不必在启动过程中将--illegal-access=deny
添加到JVM选项.像这样:
I would like to hide this warning without adding --illegal-access=deny
to JVM options during start. Something like:
System.setProperty("illegal-access", "deny");
有什么办法吗?
所有建议使用JVM选项的相关答案,我想从代码中关闭它.有可能吗?
All related answers suggesting to use JVM options, I would like to turn off this from code. Is that possible?
为了澄清-我的问题是关于通过代码而不是通过类似问题中所述的JVM参数/标志来打开此警告.
To clarify - my question is about turning this warning from the code and not via JVM arguments/flags as stated in similar questions.
推荐答案
有一些方法可以禁用非法访问警告,尽管我不建议这样做.
There are ways to disable illegal access warning, though I do not recommend doing this.
由于将警告打印到默认错误流,因此您只需关闭该流并将stderr
重定向到stdout
.
Since the warning is printed to the default error stream, you can simply close this stream and redirect stderr
to stdout
.
public static void disableWarning() {
System.err.close();
System.setErr(System.out);
}
注意:
- 此方法合并错误和输出流.在某些情况下,这可能是不可取的.
- 您不能仅通过调用
System.setErr
重定向警告消息,因为错误流的引用在JVM引导程序的早期就保存在IllegalAccessLogger.warningStream
字段中.
- This approach merges error and output streams. That may not be desirable in some cases.
- You cannot redirect warning message just by calling
System.setErr
, since the reference to error stream is saved inIllegalAccessLogger.warningStream
field early at JVM bootstrap.
一个好消息是sun.misc.Unsafe
仍可以在JDK 9中访问而不会发出警告.解决方案是在Unsafe API的帮助下重置内部IllegalAccessLogger
.
A good news is that sun.misc.Unsafe
can be still accessed in JDK 9 without warnings. The solution is to reset internal IllegalAccessLogger
with the help of Unsafe 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
}
}
这篇关于如何隐藏警告“非法反射访问"在没有JVM参数的Java 9中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!