Is it possible to monkey patch in Java?

后端 未结 9 527
有刺的猬
有刺的猬 2020-12-09 16:40

I don\'t want to discuss the merits of this approach, just if it is possible. I believe the answer to be \"no\". But maybe someone will surprise me!

Imagine you have

9条回答
  •  旧巷少年郎
    2020-12-09 16:53

    The object-oriented way of doing this would be to create a wrapper implementing IWidget, delegating all calls to the actual widget, except calculateHeight, something like:

    class MyWidget implements IWidget {
        private IWidget delegate;
        public MyWidget(IWidget d) {
            this.delegate = d;
        }
        public int calculateHeight() {
            // my implementation of calculate height
        }
        // for all other methods: {
        public Object foo(Object bar) {
            return delegate.foo(bar);
        }
    }
    

    For this to work, you need to intercept all creations of the widget you want to replace, which probably means creating a similar wrapper for the WidgetFactory. And you must be able to configure which WidgetFactory to use.

    It also depends on no client trying to cast the IWidget back to DefaultWidget...

提交回复
热议问题