【问题标题】:Java - Create an invocation handler?Java - 创建一个调用处理程序?
【发布时间】:2011-12-05 02:51:35
【问题描述】:

我正在尝试实现一个生成对象并拦截所有公共方法的工厂类。

我在这里尝试调用 2 个方法。 1:已经调用的方法 2:我的基础中的一个方法。 知道如何实现这一目标吗?

public class LoggerFactory {


    public LoggerFactory() {
    }

        // Clazz is always a class inheriting from Loggable
    public Object newInstance(Class clazz) {
        return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] {clazz}, handler);
    }

    private InvocationHandler handler = new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            // Call logStartingTime on object

            // Call invoked method on object

            // Call logEndingTime on object

            return null;
        }
    };
}

我的抽象类:

public abstract class Loggable {

       void logStartingTime() {
          log.info(“start time = ” + new Date());
          // also log some info about the state of the object
       }

       void logEndingTime() {
          log.info(“ending time = ” + new Date());
           // also log some info about the state of the object
       }
}

【问题讨论】:

    标签: java method-invocation invocationhandler


    【解决方案1】:

    我相信您可以通过 AspectJ 实现这一目标。

    【讨论】:

    • +1。更具体地说,将Loggable 作为基类没有多大意义。如果您还想包含其他一些可组合的行为怎么办? AOP 似乎是一种更好的方法。
    【解决方案2】:

    Proxy 类仅支持代理接口,不支持类。

    CGLib 确实能够从类中创建代理并执行您需要的操作。 Beans example 可以提供一个很好的起点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      相关资源
      最近更新 更多