简体   繁体   English

Java中的自动委派

[英]Automated delegation in Java

I would like to add some functionality to an object that will be generated at runtime. 我想为将在运行时生成的对象添加一些功能。 However, the interface for this object is very large (and not under my control). 但是,此对象的界面非常大(并且不受我的控制)。 I would like to wrap the object in my own class which adds the functionality I want and delegates the standard interface functionality to the original object - is there any way to do this in Java without creating a 1-line copy-paste delegator method for every method in the interface? 我想将对象包装在我自己的类中,它添加了我想要的功能并将标准接口功能委托给原始对象 - 有没有办法在Java中执行此操作而不为每个创建一行复制粘贴委托方法界面中的方法?

What I want to avoid: 我想避免的:

class MyFoo implements Foo {
  Foo wrapped;

  void myMethod() { ... }

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

What I would prefer: 我更喜欢什么:

class MyFoo implements Foo {
  Foo wrapped;

  void myMethod() { ... }

  // automatically delegate undefined methods to wrapped object
}

Sounds like you need a dynamic proxy and intercept merely the methods you want to override. 听起来你需要一个动态代理并只截取你想要覆盖的方法。

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 动态代理类的实例上的方法调用被分派到实例的调用处理程序中的单个方法 ,并使用标识被调用方法的java.lang.reflect.Method对象和包含该方法的Object类型数组进行编码。参数

(my emphasis) (我的重点)

By implementing InvocationHandler you simply create one method that receives every invocation on that object (effectively what you've described above) 通过实现InvocationHandler,您只需创建一个接收该对象上每个调用的方法(实际上您已经描述过)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM