java - Java 中的自动委托(delegate)

标签 java delegates

我想向将在运行时生成的对象添加一些功能。然而,这个对象的接口(interface)非常大(而且不在我的控制之下)。我想将对象包装在我自己的类中,它添加了我想要的功能并将标准接口(interface)功能委托(delegate)给原始对象 - 有没有办法在 Java 中执行此操作而无需为每个对象创建 1 行复制粘贴委托(delegate)方法接口(interface)中的方法?

我想避免的事情:

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您只需创建一个方法来接收对该对象的每次调用(实际上就是您上面描述的那样)

关于java - Java 中的自动委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13348215/

相关文章:

java - 到底 (args.length>0) 是什么意思?

c# - 委托(delegate)的使用

ios - 未调用 UIPickerView didSelectRow

java - 为什么尝试将 SurfaceView 与相机关联时抛出 `UnsupportedOperationException` ?

java - 覆盖 png 文件

java - 在碧 Jade 报告中将整个 sql 查询作为参数传递

java - 如何将 list<SomeType> 转换为保留所有重复键和值的映射

c# - 为什么委托(delegate)实例不总是被缓存?

c# - 为什么在 IL 代码中找不到委托(delegate)的 Invoke 方法体?

ios - 在项目选择上调用委托(delegate)方法