I like Jon Skeet's answer; it's seeing the forest instead of the trees. But to answer the question:
Assuming that the instance belongs to some interface, it's easy to use java.lang.reflect.Proxy
to do this.
public final class SynchronizedFactory {
private SynchronizedFactory() {}
public static T makeSynchronized(Class<T> ifCls, T object) {
return (T) Proxy.newProxyInstance(
object.getClass().getClassLoader(),
new Class<?>[] {ifCls},
new Handler(object));
}
static class Handler<T> implements InvocationHandler {
private final T object;
Handler(T object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
synchronized (object) {
return method.invoke(object, args);
}
}
}
}
This code is not tested, by the way. Use at your own risk.