How to change method behaviour through reflection?

后端 未结 2 1800
一整个雨季
一整个雨季 2020-12-01 15:52

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 injecti

相关标签:
2条回答
  • 2020-12-01 16:18

    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.

    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 :

    • If the class is not final and you can modify the clients, extend the existing class and overload the method, with your desired behaviour. Edit : that would work only if the method were not static !
    • Aspect programming : add interceptors to the method using 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.

    Good luck.

    0 讨论(0)
  • 2020-12-01 16:31

    I guess you could have a look at Instrumentation class which have a method redefineClasses(ClassDefintion classDefinition).

    The redefinition may change method bodies, the constant pool and attributes. The redefinition must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance.

    Hope this helps.

    References: Javadoc

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