// 可以是任意对象
```java
@Data
class User {
private String name;
private String sex;
// 具体封装的类
public class AutoCloseThreadLocal<T> implements AutoCloseable{
private ThreadLocal<T> threadLocal = new ThreadLocal<>();
public AutoCloseThreadLocal (T t) {
threadLocal.set(t);
}
public void set(T value) {
threadLocal.set(value);
}
public T get() {
return threadLocal.get();
}
public void remove() {
threadLocal.remove();
}
@Override
public void close () throws Exception {
threadLocal.remove();
}
}
// 调用
public static void main (String[] args) {
User u = new User();
u.setAge(10);
u.setName("Bob");
u.setSex("男");
try (var ctx = new AutoCloseThreadLocal(u)) {
String value = ctx.get().toString();
System.out.println(value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
野路
// 具体封装的类
// 调用
有问题请指正