static void freeDirectBuffer()

in src/main/java/org/apache/commons/crypto/stream/CryptoInputStream.java [104:129]


    static void freeDirectBuffer(final ByteBuffer buffer) {
        if (buffer != null) {
            try {
                /*
                 * Using reflection to implement sun.nio.ch.DirectBuffer.cleaner() .clean();
                 */
                final String SUN_CLASS = "sun.nio.ch.DirectBuffer";
                final Class<?>[] interfaces = buffer.getClass().getInterfaces();
                final Object[] EMPTY_OBJECT_ARRAY = {};

                for (final Class<?> clazz : interfaces) {
                    if (clazz.getName().equals(SUN_CLASS)) {
                        /* DirectBuffer#cleaner() */
                        final Method getCleaner = Class.forName(SUN_CLASS).getMethod("cleaner");
                        final Object cleaner = getCleaner.invoke(buffer, EMPTY_OBJECT_ARRAY);
                        /* Cleaner#clean() */
                        final Method cleanMethod = Class.forName("sun.misc.Cleaner").getMethod("clean");
                        cleanMethod.invoke(cleaner, EMPTY_OBJECT_ARRAY);
                        return;
                    }
                }
            } catch (final ReflectiveOperationException e) { // NOPMD
                // Ignore the Reflection exception.
            }
        }
    }