KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jfox > pool > ProxyObjectFactory


1 /* JFox, the OpenSource J2EE Application Server
2  *
3  * Distributable under GNU LGPL license by gun.org
4  * more details please visit http://www.huihoo.org/jfox
5  */

6
7 package org.jfox.pool;
8
9 import java.lang.reflect.InvocationHandler JavaDoc;
10 import java.lang.reflect.Proxy JavaDoc;
11
12 /**
13  * @author <a HREF="mailto:young_yy@hotmail.com">Young Yang</a>
14  */

15
16 public class ProxyObjectFactory extends SimpleObjectFactory {
17
18     protected Class JavaDoc invokerClass = null;
19
20     /**
21      * 使用 PoolableObjectInvocationHandler 作为默认的 InvocationHandler
22      *
23      * @param classType PoolableObject 的 Class
24      * @throws Exception
25      */

26     public ProxyObjectFactory(Class JavaDoc classType) throws Exception JavaDoc {
27         super(classType);
28         this.invokerClass = PoolableObjectInvocationHandler.class;
29     }
30
31     public ProxyObjectFactory(Class JavaDoc classType, Class JavaDoc invokerClass) throws Exception JavaDoc {
32         super(classType);
33         if(PoolableObjectInvocationHandler.class.isAssignableFrom(invokerClass)) {
34             this.invokerClass = invokerClass;
35         }
36         else {
37             throw new Exception JavaDoc(invokerClass.getName() + " not implements " + PoolableObjectInvocationHandler.class.getName());
38         }
39     }
40
41     public boolean validateObject(PoolableObject object) {
42         if(Proxy.isProxyClass(object.getClass())) {
43             object = ((PoolableObjectInvocationHandler) Proxy.getInvocationHandler(object)).getPoolableObject();
44         }
45         return super.validateObject(object);
46     }
47
48     public PoolableObject makeObject() throws Exception JavaDoc {
49         // 生成 PoolableObject
50
PoolableObject obj = (PoolableObject) classType.newInstance();
51         // 生成 PoolableObjectInvocationHandler
52
InvocationHandler JavaDoc handler = (InvocationHandler JavaDoc) invokerClass.getConstructor(new Class JavaDoc[]{PoolableObject.class}).newInstance(new Object JavaDoc[]{obj});
53
54         return (PoolableObject) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
55                 obj.getClass().getInterfaces(),
56                 handler);
57
58     }
59
60     public void destroyObject(PoolableObject object) throws Exception JavaDoc {
61         if(Proxy.isProxyClass(object.getClass())) {
62             object = ((PoolableObjectInvocationHandler) Proxy.getInvocationHandler(object)).getPoolableObject();
63         }
64         object.passivate();
65         super.destroyObject(object);
66     }
67
68 }
69
Popular Tags