How to hide warning “Illegal reflective access” in java 9 without JVM argument?

前端 未结 9 1299
Happy的楠姐
Happy的楠姐 2020-12-02 09:28

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 acce         


        
9条回答
  •  无人及你
    2020-12-02 10:10

    There are ways to disable illegal access warning, though I do not recommend doing this.

    1. Simple approach

    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);
    }
    

    Notes:

    • 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 in IllegalAccessLogger.warningStream field early at JVM bootstrap.

    2. Complicated approach without changing stderr

    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
        }
    }
    

提交回复
热议问题