package com.zhgd.xmgl.util; import com.alibaba.fastjson.JSONObject; public class ThreadLocalUtil { private static final ThreadLocal threadLocal = new ThreadLocal<>(); private ThreadLocalUtil() { } public static void set(JSONObject str) { threadLocal.set(str); } public static JSONObject get() { return threadLocal.get(); } public static JSONObject getNotNull() { if (get() == null) { threadLocal.set(new JSONObject()); } return get(); } public static T getByKey(String key, Class clz) { if (get() == null) { return null; } return (T) get().get(key); } public static void add(JSONObject str) { if (get() == null) { threadLocal.set(str); } else { get().putAll(str); // 合并两个JSONObject } } public static void addInKey(String key, Object val) { JSONObject jo = new JSONObject(); jo.put(key, val); add(jo); } public static void addInKeyIfNotExist(String key, Object val) { JSONObject jo = getNotNull(); if (!jo.containsKey(key)) { jo = new JSONObject(); jo.put(key, val); add(jo); } } public static void remove() { threadLocal.remove(); } public static void main(String[] args) { JSONObject jo = new JSONObject(); jo.put("jo", "0"); set(jo); System.out.println(threadLocal.get()); JSONObject jo1 = new JSONObject(); jo1.put("jo1", "1"); set(jo1); System.out.println(threadLocal.get()); JSONObject jo2 = new JSONObject(); jo2.put("jo2", "2"); add(jo2); System.out.println(threadLocal.get()); } }