Java javassist方法调用

4

我将使用Java Agent和Javassist来注入一些与监控相关的小代码到不同类中的不同方法中。

我的Java Agent代码:

public class ConverterAgent implements ClassFileTransformer {

public static void premain(String args, Instrumentation instrumentation){
    System.out.println(">>>>>>>>>> Intializing Java agent <<<<<<<<<<");
    ConverterAgent transformer = new ConverterAgent();
    instrumentation.addTransformer(transformer);

}

public static void agentmain(String args, Instrumentation instrumentation){
    System.out.println(">>>>>>>>>> Intializing Java agent <<<<<<<<<<");
    ConverterAgent transformer=new ConverterAgent();
    instrumentation.addTransformer(transformer); 
}


@Override
public byte[] transform(final ClassLoader loader, 
        String className, 
        Class<?> classBeingRedefined, 
        ProtectionDomain protectionDoman, 
        byte[] classFileBuffer)
                throws IllegalClassFormatException {



//javassist code goes here


return classFileBuffer;

}

}

我的javassist注入代码如下:
if ("className1".equals(className)){

//code

}


 if ("className2".equals(className)){

//same code as in first class

}


if ("className3".equals(className)){

//same code as in first and second class

}

我正在多次注入完全相同的代码,希望优化我的过程并为每次注入调用一个方法,这样就不必一遍又一遍地复制相同的代码。但是这里是我遇到的问题,我应该使用什么方法类型以及除了类和方法名之外需要哪些参数。

1个回答

3

转换方法中,您正在获取类字节码,然后返回经过修改的“新”类字节码。

这意味着您要返回的肯定是包含在转换方法中所需信息的byte[]。

因此,您的方法应该像这样:

public class DynamicTransformer implements ClassFileTransformer {

    public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined,
    ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

        byte[] byteCode = classfileBuffer;

        // into the transformer will arrive every class loaded so you filter 
        // to match only what you need
        if (className.equals("com/full/path/to/be/instrumented/className1") ||
            className.equals("com/full/path/to/be/instrumented/className2") ||
            className.equals("com/full/path/to/be/instrumented/className3") ) {

            byteCode = myMethodThatTransform(className, byteCode);
        }

        return byteCode;
    }


    public byte[] myMethodThatTransform(String className, byte[] byteCode){\
        try {
            // retrive default Javassist class pool
            ClassPool cp = ClassPool.getDefault();
            // get from the class pool our class with this qualified name
            CtClass cc = cp.get(className);
            // get all the methods of the retrieved class
            CtMethod[] methods = cc.getDeclaredMethods()
            for(CtMethod meth : methods) {
                // The instrumentation code to be returned and injected
                final StringBuffer buffer = new StringBuffer();
                String name = meth.getName();
                // just print into the buffer a log for example
                buffer.append("System.out.println(\"Method " + name + " executed\" );");
                meth.insertBefore(buffer.toString())
            }
            // create the byteclode of the class
            byteCode = cc.toBytecode();
            // remove the CtClass from the ClassPool
            cc.detach();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return byteCode;
    }
}

1
如果您使用地图而不是多个由||分隔的等于检查,那么效率会更高。 - Sean Patrick Floyd
1
非常感谢,你解决了我的问题,我相信其他人也会发现你的代码非常有用。 - stef

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接