get Generic Value from ThreadLocal - Java java.lang

Java examples for java.lang:ThreadLocal

Description

get Generic Value from ThreadLocal

Demo Code


//package com.java2s;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static <T> T getValue(ThreadLocal<T> variable, Thread key) {
        try {//  w  ww .  java2s .c o  m
            Field field = Thread.class.getDeclaredField("threadLocals");
            field.setAccessible(true);
            Object entryMap = field.get(key);
            if (entryMap == null)
                return null;
            Method getEntryMethod = entryMap.getClass().getDeclaredMethod(
                    "getEntry", ThreadLocal.class);
            getEntryMethod.setAccessible(true);
            Object entry = getEntryMethod.invoke(entryMap, variable);
            if (entry == null)
                return null;
            Field valueField = entry.getClass().getDeclaredField("value");
            valueField.setAccessible(true);

            return (T) valueField.get(entry);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials