001package org.apache.log4j;
002
003import java.lang.reflect.Field;
004import java.lang.reflect.Method;
005
006import org.apache.log4j.helpers.ThreadLocalMap;
007
008public class MDCFriend {
009
010    public static void fixForJava9() {
011        try {
012            Field mdcField = MDC.class.getDeclaredField("mdc");
013
014            MDC mdcSingleton = (MDC) mdcField.get(null);
015            Field tlmField = MDC.class.getDeclaredField("tlm");
016
017            Field java1Field = MDC.class.getDeclaredField("java1");
018            Object mdcSingleton_tlm = tlmField.get(mdcSingleton);
019
020            if (mdcSingleton_tlm == null) {
021                tlmField.set(mdcSingleton, new ThreadLocalMap());
022                java1Field.setBoolean(mdcSingleton, false);
023                setRemoveMethod(mdcSingleton);
024            }
025        } catch (SecurityException e) {
026            e.printStackTrace();
027        } catch (NoSuchFieldException e) {
028            e.printStackTrace();
029        } catch (IllegalArgumentException e) {
030            e.printStackTrace();
031        } catch (IllegalAccessException e) {
032            e.printStackTrace();
033        }
034
035    }
036
037    private static void setRemoveMethod(org.apache.log4j.MDC mdc) {
038        try {
039            Method removeMethod = ThreadLocal.class.getMethod("remove");
040            Field removeMethodField = MDC.class.getDeclaredField("removeMethod");
041            removeMethodField.setAccessible(true);
042            removeMethodField.set(mdc, removeMethod);
043        } catch (NoSuchMethodException e) {
044            e.printStackTrace();
045        } catch (SecurityException e) {
046            e.printStackTrace();
047        } catch (NoSuchFieldException e) {
048            e.printStackTrace();
049        } catch (IllegalArgumentException e) {
050            e.printStackTrace();
051        } catch (IllegalAccessException e) {
052            e.printStackTrace();
053        }
054
055    }
056}