Java中的自动委派

前端之家收集整理的这篇文章主要介绍了Java中的自动委派前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想为将在运行时生成的对象添加一些功能.但是,此对象的界面非常大(并且不受我的控制).我想将对象包装在我自己的类中,它添加了我想要的功能并将标准接口功能委托给原始对象 – 有没有办法在 Java中执行此操作而不为每个创建一行复制粘贴委托方法界面中的方法

我想避免的:

class MyFoo implements Foo {
  Foo wrapped;

  void myMethod() { ... }

  void interfaceMethod1() wrapped.interfaceMethod1();
  int interfaceMethod2() wrapped.interfaceMethod2();
  // etc etc ...
}

我更喜欢什么:

class MyFoo implements Foo {
  Foo wrapped;

  void myMethod() { ... }

  // automatically delegate undefined methods to wrapped object
}

解决方法

听起来你需要一个 dynamic proxy并且仅截取你想要覆盖的方法.

A dynamic proxy class is a class that implements a list of interfaces
specified at runtime such that a method invocation through one of the
interfaces on an instance of the class will be encoded and dispatched
to another object through a uniform interface. Thus,a dynamic proxy
class can be used to create a type-safe proxy object for a list of
interfaces without requiring pre-generation of the proxy class,such
as with compile-time tools. Method invocations on an instance of a
dynamic proxy class are dispatched to a single method in the
instance’s invocation handler
,and they are encoded with a
java.lang.reflect.Method object identifying the method that was
invoked and an array of type Object containing the arguments

(我的重点)

通过实现InvocationHandler,您只需创建一个接收该对象上每次调用方法(实际上您已经在上面描述过)

原文链接:https://www.f2er.com/java/121876.html

猜你在找的Java相关文章