CtMethod CtMethod=ctClass. GetDeclaredMethod (methodName);//get this method instance
//create a new method, for the original copy of the original method, the name name
CtMethod newMethod=CtNewMethod. Copy (CtMethod, methodName, ctClass, null);
//define a method name used to describe the modified bytecode before the original method of
String oldMethodName=methodName + "$old";
//amend the name of the original method, avoid conflict and the newly added method name
CtMethod. Elegantly-named setName (oldMethodName);
//build new method body
The StringBuilder bodyStr=new StringBuilder ();
BodyStr. Append (" {");
BodyStr. Append (" long startTime=System. CurrentTimeMillis (); \n");
//call the method code, similar to the method (); All the parameters ($$) said
BodyStr. Append (oldMethodName). Append (" ($$); \n");
BodyStr. Append (" long endTime=System. CurrentTimeMillis (); \n");
String outputStr="System. Out. Println (" this method "+ methodName
+ cost: \ "" + (endTime - startTime) + " Ms. \ "); \n";
BodyStr. Append (outputStr);
BodyStr. Append ("} ");
//set the new target method method body
NewMethod. SetBody (bodyStr. ToString ());
//add new method, name of the original method has been modified for oldMethodName, call will call to the new target method
CtClass. AddMethod (newMethod);
CodePudding user response:
wan chun on the ground floorCodePudding user response:
Adding a field or method is impossible as it is today, only the code evolution VM supports it as of today and it is doubtful if this feature (top service it to its.CodePudding user response:
With the an AgentBuilder, you should register a Listener to see if the errors happen during retransformation. You probably should set the disableClassFormatChanges () as the business, the JVM does not support adding the methods or fields to a class that already is defined.CodePudding user response: