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 with a callback to create thread-specific objects
48 * Interface class of the service to proxy.
50 * Callback to create the object if it does not exist. When null,
51 * then no initialization is done.
53 public SerializableProxyFactory(Class<T> aClass, T aSvc) {
54 if (!aClass.isInterface()) {
55 throw new IllegalArgumentException("Class " + aClass.getName() +
56 " is not an interface");
58 if (!aClass.isInstance(aSvc)) {
59 throw new IllegalArgumentException("Object " + aSvc +
60 " cannot be cast to " + aSvc.getClass());
64 proxy = createProxy();
69 * Gets the underlying service.
78 * Gets the serializable proxy that delegates to the object passed in the constructor.
86 private T createProxy() {
87 InvocationHandler handler = new SerializableInvocationHandler(svc,
89 Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(),
90 new Class[] { clazz });
93 proxyObj = (T) proxyClass.getConstructor(
94 new Class[] { InvocationHandler.class }).newInstance(
95 new Object[] { handler });
97 } catch (Exception e) {
98 throw new RuntimeException("Could not create proxy for " +