01: /* JFox, the OpenSource J2EE Application Server
02: *
03: * Copyright (C) 2002 huihoo.org
04: * Distributable under GNU LGPL license
05: * See the GNU Lesser General Public License for more details.
06: */
07:
08: package org.huihoo.jfox.pool;
09:
10: import java.lang.reflect.Proxy;
11: import java.lang.reflect.InvocationHandler;
12:
13: /**
14: *
15: * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
16: */
17:
18: public class ProxyObjectFactory extends ObjectFactorySupport {
19:
20: protected Class invokerClass = null;
21:
22: /**
23: * 使用 PoolableObjectInvocationHandler 作为默认的 InvocationHandler
24: * @param classType PoolableObject 的 Class
25: * @throws Exception
26: */
27: public ProxyObjectFactory(Class classType) throws Exception {
28: super (classType);
29: this .invokerClass = PoolableObjectInvocationHandler.class;
30: }
31:
32: public ProxyObjectFactory(Class classType, Class invokerClass)
33: throws Exception {
34: super (classType);
35: if (PoolableObjectInvocationHandler.class
36: .isAssignableFrom(invokerClass)) {
37: this .invokerClass = invokerClass;
38: } else {
39: throw new Exception(invokerClass.getName()
40: + " not implements "
41: + PoolableObjectInvocationHandler.class.getName());
42: }
43: }
44:
45: public boolean validateObject(PoolableObject object) {
46: if (Proxy.isProxyClass(object.getClass())) {
47: object = ((PoolableObjectInvocationHandler) Proxy
48: .getInvocationHandler(object)).getPoolableObject();
49: }
50: return super .validateObject(object);
51: }
52:
53: public PoolableObject makeObject() throws Exception {
54: // 生成 PoolableObject
55: PoolableObject obj = (PoolableObject) classType.newInstance();
56: // 生成 PoolableObjectInvocationHandler
57: InvocationHandler handler = (InvocationHandler) invokerClass
58: .getConstructor(new Class[] { PoolableObject.class })
59: .newInstance(new Object[] { obj });
60:
61: return (PoolableObject) Proxy.newProxyInstance(Thread
62: .currentThread().getContextClassLoader(), obj
63: .getClass().getInterfaces(), handler);
64:
65: }
66:
67: public void destroyObject(PoolableObject object) throws Exception {
68: if (Proxy.isProxyClass(object.getClass())) {
69: object = ((PoolableObjectInvocationHandler) Proxy
70: .getInvocationHandler(object)).getPoolableObject();
71: }
72: object.passivate();
73: super.destroyObject(object);
74: }
75:
76: }
|