Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change method behaviour through reflection?

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 ?

Thanks !

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.

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

like image 710
dev Avatar asked Apr 12 '13 08:04

dev


People also ask

What is reflection method?

Reflection gives us information about the class to which an object belongs and also the methods of that class that can be executed by using the object. Through reflection, we can invoke methods at runtime irrespective of the access specifier used with them.

What is reflection in unit testing?

Introduction. ReflectionTestUtils is a part of Spring Test Context framework. It is a collection for reflection-based utility methods used in a unit, and integration testing scenarios to set the non-public fields, invoke non-public methods, and inject dependencies.

What is reflection and how does it help to manipulate Java code?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.


1 Answers

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.

like image 59
Pierre Henry Avatar answered Sep 20 '22 14:09

Pierre Henry