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

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

问题描述

我有一些旧的code,这就是所谓的由多个客户端AA静态方法。我明明没有选项覆盖它,或者通过依赖注入改变行为。我不允许修改现有的类。

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 ?

谢谢!

编辑:有对我有什么可以改变一些混乱/修改。我不能改变任何现有的类/方法 - 但我可以添加更多的类到项目中。我可以用现有的类做的最好的注释它们。这是所有做是为了避免在现有的code破坏任何东西 - 这意味着一个完整的一轮测试的一个大项目

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...

总之,反射不允许你改变code行为,它只能探索当前code,调用方法和constuctors,改变字段的值,那样的事情。

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.

如果你想真正改变一个方法的行为,你将不得不使用一个字节code操作库,如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...

模式,可以帮助你:

  • 如果该类不是最终版本,可以通过修改客户端,扩展现有的类和重载方法,用你想要的行为。编辑:这只会工作,如果该方法不是静态
  • 看点编程:添加使用AspectJ拦截器的方法

总之,最合乎逻辑的事情是要找到一个方法来修改现有的类,变通方法只会让你的code更加复杂和难以维护。

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天全站免登陆