![](/img/trans.png)
[英]javassist.CannotCompileException when calling a method with Varargs
[英]Java javassist method calling
所以我将java代理与javassist一起使用,以便将一些小的监视相关代码注入到不同类中的不同方法中。
我的java代理代码:
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
}
所以我多次注入相同的代码,我想优化我的进程并为每次注入调用一个方法,所以我不必一遍又一遍地复制相同的代码。 但是这里是我遇到问题的地方,我应该使用什么方法类型以及除了类和方法名称之外还需要什么参数。
这意味着确定要返回的是包含transform方法所需信息的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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.