如何通过反射改变方法行为? [英] How to change method behaviour through reflection?

查看:26
本文介绍了如何通过反射改变方法行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些遗留代码中有一个静态方法,它被多个客户端调用.我显然没有选择覆盖它,或者通过依赖注入改变行为.我不允许修改现有的类.

I have a a static method in some legacy code, which is called by multiple clients. I obviously have no options to override it, or change behaviour through dependency injection. I am not allowed to modify the existing class.

我现在想做的是使用反射更改行为(该方法 - 具有相同的签名和返回类型).

What I want to do now is change the behaviour (that method - with the same signature and return type) using reflection.

有可能吗?如果没有,有什么设计模式可以拯救我吗?

Is it possible ? If not, can any design pattern rescue me ?

谢谢!

对我可以更改/修改的内容有些困惑.我无法更改任何现有的类/方法 - 但我可以向项目添加更多类.我对现有类能做的最好的事情就是对它们进行注释.这样做是为了避免破坏现有代码中的任何内容 - 这意味着对大型项目进行完整的一轮测试.

EDIT : There is some confusion on what can I change/modify. I cannot change any existing class/method - but I can add more classes to the project. The best I can do with the existing classes is annotate them. This is all done to avoid breaking anything in the existing code - which means a complete round of testing for a big project.

编辑 2:java.lang.Instrumentation 不适用于 Android - 否则听起来很合适!

EDIT 2 : java.lang.Instrumentation is not available for Android - or else it sounds like a good fit !

推荐答案

听起来很奇怪的要求...

Sounds like a weird requirement...

无论如何,反射不允许您更改代码行为,它只能探索当前代码、调用方法和构造函数、更改字段值等.

Anyway, reflection does not allow you to change code behaviour, it can only explore current code, invoke methods and constuctors, change fields values, that kind of things.

如果你想真正改变一个方法的行为,你必须使用字节码操作库,比如 ASM.但这不会很容易,可能不是一个好主意......

If you want to actually change the behaviour of a method you would have to use a bytecode manipulation library such as ASM. But this will not be very easy, probably not a good idea...

可能对您有帮助的模式:

Patterns that might help you :

  • 如果类不是最终类,您可以修改客户端,扩展现有类并重载方法,并使用您想要的行为.只有当方法不是静态的时候才有效!
  • 方面编程:使用 AspectJ 向方法添加拦截器

无论如何,最合乎逻辑的做法是找到一种方法来修改现有的类,变通方法只会使您的代码更加复杂且难以维护.

Anyway, the most logical thing to do would be to find a way to modify the existing class, work-arounds will just make your code more complicated and harder to maintain.

祝你好运.

这篇关于如何通过反射改变方法行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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