在 Proxy 对象(实现的对象java.lang.reflect.InvocationHandler
)中,我试图在代理对象中设置一个实例变量。
如下所示:
public class ServiceProxy implements InvocationHandler {
private final Object proxiedObject;
private ServiceProxy(final Object object) {
this.proxiedObject = object;
}
public static Object newInstance(final Object object) {
return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new ServiceProxy(object));
}
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
Object result = null;
MyObject mo = new MyObject();
// Is the following safe when the proxiedObject is being acceessed by multiple threads?
final Field sessionField = this.proxiedObject.getClass().getSuperclass().getDeclaredField("mo");
sessionField.setAccessible(true);
sessionField.set(this.object, mo);
result = method.invoke(this.proxiedObject, args);
return result;
}
}
这安全吗?
编辑:
实际代码:
Object result = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession()
// Is the following save when the proxiedObject is being acceessed by multiple threads?
final Field sessionField = this.proxiedObject.getClass().getSuperclass().getDeclaredField("session");
sessionField.setAccessible(true);
sessionField.set(this.object, session);
result = method.invoke(this.proxiedObject, args);
return result;
Edit2 : 代理对象是从 GWT 客户端调用的,该客户端同时调用同一代理对象的多个方法。发生这种情况时,我让会话实例字段(代理类)以意想不到的方式关闭和打开。