I am trying to trace method calls in java, currently I am using javassist library and my code is:
for (CtMethod meth : methods) {
String method = meth.getName();
try {
meth.instrument(new ExprEditor() {
public void edit(MethodCall m) throws CannotCompileException {
StringBuffer buffer = new StringBuffer();
StringBuffer bufferEnd = new StringBuffer();
String formatMessage = "String instMessage=new java.text.MessageFormat(\"{0},{1},{2}, has started execution,{3},{4}\").format(new String[]{\""
+ "returnType" + " " + meth.getLongName()
+ "\",\"" + cc.getSimpleName() + "\",\"" + method
+ "\", new java.util.Date().toString()"
+ ",java.lang.Thread.currentThread().getId()+\"\"});";
buffer.append(formatMessage);
buffer.append("org.springframework.samples.jpetstore.domain.logic.Log.trace( instMessage);");
String formatMessageEnd = "String instMessageEnd=new java.text.MessageFormat(\"{0},{1},{2}, has finished execution,{3},{4}\").format(new String[]{\""
+"returnType" + " " + meth.getLongName()
+ "\",\"" + cc.getSimpleName() + "\",\"" + method
+ "\", new java.util.Date().toString()"
+ ",java.lang.Thread.currentThread().getId()+\"\"});";
bufferEnd.append(formatMessageEnd);
bufferEnd.append("org.springframework.samples.jpetstore.domain.logic.Log.trace(instMessageEnd);");
String start = buffer.toString();
String stop = bufferEnd.toString();
m.replace("{ try {" + start + " $_ = $proceed($$); } finally { " + stop + " } }");
}
});
} catch (CannotCompileException e) {
System.out.println("******error:" + cc.getSimpleName() + " - " + method);
System.out.println(e.getMessage());
e.printStackTrace();
}
}
that's worked for me except for getter methods, for example if I have class called A with getB() method It still like the original without instrument, any idea how can I fix this. note I will appreciate if you have another method to get method calls (without using AOP) to get for example:
ClassA.method() **called** ClassB.method() at date()
ClassB.method() **return to** ClassA.method() at date()
Over the years, I have found this is one of the most challenging Java problems, to get a framework or library to do. We have to use AOP or reflection, please also try AspectJ
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.