Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-创建调用处理程序?_Java_Method Invocation_Invocationhandler - Fatal编程技术网

Java-创建调用处理程序?

Java-创建调用处理程序?,java,method-invocation,invocationhandler,Java,Method Invocation,Invocationhandler,我试图实现一个工厂类,该类生成对象并拦截所有公共方法 我在这里尝试调用两个方法。1:已调用的方法2:我的库中的方法。 你知道我怎样才能做到这一点吗 public class LoggerFactory { public LoggerFactory() { } // Clazz is always a class inheriting from Loggable public Object newInstance(Class clazz) {

我试图实现一个工厂类,该类生成对象并拦截所有公共方法

我在这里尝试调用两个方法。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
       }
}
该类仅支持代理接口,不支持类

能够从类中创建代理并执行所需操作。可以提供一个良好的起点。

该类仅支持代理接口,不支持类


能够从类中创建代理并执行所需操作。这可能是一个很好的起点。

我相信你可以通过。

我相信你可以通过。

+1来完成。更具体地说,将Loggable作为基类没有多大意义。如果您还想包含一些其他可组合行为,该怎么办?AOP似乎是一个更好的方法。更具体地说,将Loggable作为基类没有多大意义。如果您还想包含一些其他可组合行为,该怎么办?AOP似乎是一种更好的方法。