我的javaagent中止,没有发现错误

时间:2015-08-17 15:55:05

标签: java javassist javaagents

我想使用javaagent和javassist来拦截方法执行时间,但是方法拦截方法中止没有错误。

代理:

import java.lang.instrument.Instrumentation;

public class Agent {
public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println("in Agent#premain");
         inst.addTransformer(new TimingTransformer());
}}

变压器

public class JassistTiming {
public static byte[] addTiming(String clazz, String mname) throws NotFoundException, CannotCompileException,
        IOException {
    System.out.println("addTiming, clazz: " + clazz);
    CtClass clas = ClassPool.getDefault().get(clazz);
    System.out.println("after get clas: " + clas);
    CtMethod mold = clas.getDeclaredMethod(mname);

    String nname = mname + "$impl";
    mold.setName(nname);
    CtMethod mnew = CtNewMethod.copy(mold, mname, clas, null);

    String type = mold.getReturnType().getName();
    StringBuffer body = new StringBuffer();
    body.append("{\nlong start = System.currentTimeMillis();\n");
    if (!"void".equals(type)) {
        body.append(type + " result = ");
    }
    body.append(nname + "($$);\n");

    body.append("System.out.println(\"Call to method " + mname
            + " took \" +\n (System.currentTimeMillis()-start) + " + "\" ms.\");\n");
    if (!"void".equals(type)) {
        body.append("return result;\n");
    }
    body.append("}");

    mnew.setBody(body.toString());
    clas.addMethod(mnew);
    return clas.toBytecode();
}
}

App.java

class TimeConsume {
public void doSomething(Integer param) {
    try {
        System.out.println("in doSomething...");
        Thread.sleep(param * 1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}
public class App {
public static void main( String[] args ) throws Exception
{
    TimeConsume tc = new TimeConsume();
    tc.doSomething(3);
}}

输出:

in Agent#premain
in TimingTransformer
addTiming, clazz: demo.design.pattern.TimeConsume
in doSomething...

“get clas后”不打印且没有错误

1 个答案:

答案 0 :(得分:0)

这是类路径问题,我指定了类路径,现在好了