/* ================================================================== * Created [2009-4-27 下午11:32:55] by Jon.King * ================================================================== * TSS * ================================================================== * mailTo:jinpujun@hotmail.com * Copyright (c) Jon.King, 2009-2012 * ================================================================== */ package com.jinhe.tss.core.cachepool.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import org.apache.log4j.Logger; import com.jinhe.tss.core.exception.BusinessException; /** * <p> BaseInvocationHandler.java </p> * InvocationHandler基类 * * @author Jon.King 2007-1-5 */ public abstract class BaseInvocationHandler implements InvocationHandler{ protected Logger log = Logger.getLogger(this.getClass()); private Object target; //拦截的对象 private String[] invokeMethods; //需要拦截的方法,为空则拦截任何方法 /** * @param target 拦截的对象 * @param invokeMethods 需要拦截的方法 */ public BaseInvocationHandler(Object target, String[] invokeMethods){ this.invokeMethods = invokeMethods; this.target = target; } public BaseInvocationHandler(Object target){ this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //如果没有指定拦截的方法列表,则拦截接口中所有方法。 boolean invoke = (invokeMethods == null || (invokeMethods.length > 0 && Arrays.asList(invokeMethods).contains(method.getName()))); Object returnVal; Object beforeReturnVal = null; try { if(invoke){ //执行拦截前操作 beforeReturnVal = (Long) before(target, method, args); } // 执行方法,并获取返回值 returnVal = method.invoke(target, args); return returnVal; } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw new BusinessException("unexpected invocation exception: " + e.getMessage()); } finally { if(invoke) { //执行拦截后操作 after(target, method, args, beforeReturnVal); } } } /** * 定义方法执行前的操作 * @param target * @param method * @param args * @return */ protected abstract Object before(Object target, Method method, Object[] args); /** * 定义方法执行后的操作 * @param target * @param method * @param args * @param beforeReturnVal */ protected abstract void after(Object target, Method method, Object[] args, Object beforeReturnVal); }