Java自动委托 [英] Automated delegation in Java

查看:147
本文介绍了Java自动委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为在运行时生成的对象添加一些功能。但是,该对象的接口非常大(而不在我的控制之下)。我想将对象包装在我自己的类中,它添加了我想要的功能,并将标准接口功能委托给原始对象 - 有没有办法在Java中完成,而不需要为每一个都创建一行复制粘贴委托方法方法在界面?



我想避免的:

  MyFoo类实现Foo {
Foo包装;

void myMethod(){...}

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

我想要什么:

  class MyFoo implements Foo {
Foo wrapped;

void myMethod(){...}

//自动将未定义的方法委托给包装对象
}


解决方案

听起来你需要一个动态代理,只拦截您要覆盖的方法。



< blockquote>

动态代理类是一个实现在运行时指定的接口
的列表的类,以便通过类的一个实例上的
接口之一调用方法通过统一的界面编码并将
分派给另一个对象。因此,动态代理
类可以用于为
接口列表创建一个类型安全的代理对象,而不需要代理代理类,比如
,与编译时一样工具在
动态代理类的实例上的方法调用发送到
实例的调用处理程序中的单个方法,并且它们被编码为
java.lang标识调用
的方法的方法对象和包含参数的类型Object的数组


(我的重点)



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


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?

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

(my emphasis)

By implementing InvocationHandler you simply create one method that receives every invocation on that object (effectively what you've described above)

这篇关于Java自动委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆