Automated delegation in Java

前端 未结 1 920
小蘑菇
小蘑菇 2021-01-05 17:49

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 w

相关标签:
1条回答
  • 2021-01-05 18:07

    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)

    0 讨论(0)
提交回复
热议问题