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

package org.jfox.pool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 需要拦截 PoolableObject 的方法调用的时候，使用 Proxy 机制来访问
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class PoolableObjectInvocationHandler implements InvocationHandler {

    private PoolableObject poolableObject = null;
    private boolean passivated = false;

    public PoolableObjectInvocationHandler() {

    }

    public PoolableObjectInvocationHandler(PoolableObject poolableObject) {
        this.poolableObject = poolableObject;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(passivated) throw new NullPointerException("pooled object had passviated.");

        // 默认只拦截 passivate 方法，如果要拦截其他方法，可以写一个子类
        if(method.getName().equals("passivate") && method.getParameterTypes().length == 0) {
            passivated = true;
        }
        return method.invoke(poolableObject, args);
    }

    public PoolableObject getPoolableObject() {
        return poolableObject;
    }

}
