Is it possible to monkey patch in Java?

后端 未结 9 431
有刺的猬
有刺的猬 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 17:06

    You can try using tools like PowerMock/Mockito. If you can mock in tests, you can mock in production too.

    However these tools are not really designed to be used that way, so you'll have to prepare the environment yourself and won't be able to use the JUnit runners like you do in tests...

    0 讨论(0)
  • 2020-12-09 17:06

    Well, I keep trying to post suggestions, and then I see that they won't work or that you've already mentioned you tried them.

    The best solution I can think of is to subclass WindowDisplayFactory, then in the subclass's createView() method, first call super.createView(), then modify the object returned to completely throw out the widget and replace it with an instance of the subclass that does what you want. But the widget is used to initialize stuff, so you'd have to go change all of those.

    Then I think of using reflection on the returned object from createView() and trying to fix things up that way, but again, that's hairy because so much stuff was initialized with the widget. I think I would try to use that approach, though, if it was simple enough to justify it over copying and pasting.

    I'll be watching this, plus thinking to see if I can come up with any other ideas. Java Reflection sure is nice, but it can't beat the dynamic introspection I've seen available in languages such as Perl and Python.

    0 讨论(0)
  • 2020-12-09 17:14

    One ugly solution would be to put your own implementation of DefaultWidget (with same FQCN) earlier on the Classpath than the normal implementation. It's a terrible hack, but every other approach that I can think of is even worse.

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