在Java中对该类进行任何方法调用之前调用方法

时间:2016-09-07 12:18:00

标签: java

有没有办法在每次调用该类的任何方法时都可以在类中执行一个方法。

我将简要介绍一下我的情景:

Class Util{

   private isConnected(){
      if(!xxxapi.connected())
            throw new MyException(....)
}
   public createFile(){....}
   public removeFile(){....}
}

所以,每当我调用new Util.createFile()时,我希望在createFile()实际启动之前调用isConnected()。 显然我可以在每个方法的开头每次调用isConnected(),但我想知道我是否可以有另一个解决方案。

是否有针对此类情况的其他建议/解决方案。

1 个答案:

答案 0 :(得分:9)

您应该编写一个InvocationHandlerhttp://docs.oracle.com/javase/7/docs/api/java/lang/reflect/InvocationHandler.html)来拦截对象的调用,然后反过来(使用反射API)首先调用isConnected()方法,然后调用方法。打电话了。

样品: Util接口:

public interface Util {

    void isConnected();

    void createFile();

    void removeFile();

}

Util调用处理程序:

public class UtilInvocationHandler implements InvocationHandler {

    private Util util = new UtilImpl();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {

        // look up isConnectedMethod
        Method isConnectedMethod = util.getClass().getMethod("isConnected");

        // invoke the method
        isConnectedMethod.invoke(util);

        // process result of the above call here

        // invoke the method to which the call was made
        Object returnObj = method.invoke(util, args);

        return returnObj;
    }

    private static class UtilImpl implements Util {
        public void isConnected(){
            System.out.println("isConnected()");
        }

        public void createFile(){
            System.out.println("createFile()");
        }

        public void removeFile(){
            System.out.println("removeFile()");
        }
    }
}

对象初始化:

    Util util = (Util) Proxy.newProxyInstance(
                                   Util.class.getClassLoader(), 
                                   new Class[] {Util.class}, 
                                   new UtilInvocationHandler());
相关问题