2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.general;
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.Proxy;
23 * Serializable proxy factory that allows to create serializable proxies to
24 * objects that are themselves not serializable.
28 * This class does not do any cleanup so it is recommended to only use this in
33 * @author Erik Brakkee
37 public class SerializableProxyFactory<T> {
44 * Constructs the factory.
47 * Interface class of the service to proxy.
49 public SerializableProxyFactory(Class<T> aClass) {
54 * Constructs the factory with a callback to create thread-specific objects
58 * Interface class of the service to proxy.
60 * Callback to create the object if it does not exist. When null,
61 * then no initialization is done.
63 public SerializableProxyFactory(Class<T> aClass, T aSvc) {
64 if (!aClass.isInterface()) {
65 throw new IllegalArgumentException("Class " + aClass.getName() +
66 " is not an interface");
68 if (!aClass.isInstance(aSvc)) {
69 throw new IllegalArgumentException("Object " + aSvc +
70 " cannot be cast to " + aSvc.getClass());
74 proxy = createProxy();
79 * Gets the underlying service.
88 * Gets the proxy that delegates to the thread-specific instance set by
89 * {@link #set(Object)}
97 private T createProxy() {
98 InvocationHandler handler = new SerializableInvocationHandler(svc,
100 Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(),
101 new Class[] { clazz });
104 proxyObj = (T) proxyClass.getConstructor(
105 new Class[] { InvocationHandler.class }).newInstance(
106 new Object[] { handler });
108 } catch (Exception e) {
109 throw new RuntimeException("Could not create proxy for " +