0

My query is related to bytecode manipulation using ASM.

I have one method as follows --

/*Original method code*/  
String str ="abs";    
// create object of SampleClass2 // constructor calling   
SampleClass2 sample = new SampleClass2();   
// call instance method         
sample.PrintMe(str); 

In the above method, I want to change the SampleClass2() constructor to one static method call which will return same SampleClass2 object after doing some logic. So after that my method will look something like this.

/*
 * After bytecode manipulation*
*/
String str ="abs";  
// get a  constructor using  static call   
SampleClass2 sample = StaticClass.getSampleClass2Object(); 
sample.PrintMe(str);

Please tell me how can I achieve this using ASM bytecode manipulation. Do we need to change the existing bytecode stack for the same like DUP

vijay
  • 2,646
  • 2
  • 23
  • 37
Ashiq Sayyad
  • 111
  • 2
  • 5

1 Answers1

0

The main problem is that the object is first created with a "new" instruction, followed by the call to the constructor. You'd have to replace both the "new" and the constructor call, which might be difficult to achieve. If you want to go along that road, make sure to check out Chapter 8 (Tree API -> Method Analysis) p 115 in the ASM documentation.

However, if that is enought, you could simply add a call to a static method to do some post instantiation logic, which is fairly simple. Just find the constructor call, and add a static invocation to a method afterwards which takes a SampleClass2 as parameter and returns a SampleClass2 (probably the same instance)

ruediste
  • 2,434
  • 1
  • 21
  • 30