标签: invocationhandler

JAVA:与接口的实现相比,InvocationHandler 有哪些优势?

今天在课堂上,我们讨论了 Java 编程中的反射。今天课程的一部分是关于在 Java 中使用InvocationHandler,而不仅仅是实现一个接口。当我问老师使用调用处理程序有什么好处时,没有明确的答案。假设我们有一个接口插件

public interface Plugin {
    void calculate(double a, double b);
    String getCommand();
}
Run Code Online (Sandbox Code Playgroud)

您可以在Multiply类中轻松实现此接口

public class Multiply implements Plugin {
    @Override
    public void calculate(double a, double b){
         return a * b;
    }

    @Override
    public String getCommand(){
         return "*";
    }
}
Run Code Online (Sandbox Code Playgroud)

那么为什么我更喜欢使用InvocationHandler 的另一个实现?

 public class MyMock {
     public static Object createMock(Class myClass) {
         InvocationHandler handler = new MyInvocationHandler();
         Object result = Proxy.newProxyInstance(myClass.getClassLoader(), new Class[]{myClass}, handler);
         return result;
     }
 }
Run Code Online (Sandbox Code Playgroud)

提前致谢 …

java implementation interface mocking invocationhandler

10
推荐指数
3
解决办法
3001
查看次数