I need to extend the behavior of an instance, but I don't have access to the original source code of that instance. For example:
/* I don't have the source code for this class, only the runtime instance */
Class AB
{
public void execute();
}
in my code I would to intercept every call to execute, compute some sutff and then call the original execute, something like
/* This is how I would like to modify the method invokation */
SomeType m_OrgExecute;
{
AB a = new AB();
m_OrgExecute = GetByReflection( a.execute );
a.execute = MyExecute;
}
void MyExecute()
{
System.Console.Writeln( "In MyExecute" );
m_OrgExecute();
}
Is that possible?
Does anyone have a solution for this problem?
It looks like you want the Decorator pattern.
class AB
{
public void execute() {...}
}
class FlaviosABDecorator : AB
{
AB decoratoredAB;
public FlaviosABDecorator (AB decorated)
{
this.decoratedAB = decorated;
}
public void execute()
{
FlaviosExecute(); //execute your code first...
decoratedAB.execute();
}
void FlaviosExecute() {...}
}
You'd then have to modify the code where the AB
object is used.
//original code
//AB someAB = new AB();
//new code
AB originalAB = new AB();
AB someAB = new FlaviosABDecorotor(originalAB);
/* now the following code "just works" but adds your method call */
There is no way to do this directly via reflection, etc.
In order to have your own code injected like this, you'll need to create a modified version of their assembly, and use some form of code injection. You cannot just "change a method" of an arbitrary assembly at runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With