我试图通过在每个检测方法中添加几行代码来将方法的名称写入文件。我正在使用 Javassist。
这是我的代码:
public static void addInstrumentation(CtClass ctClass, CtMethod ctMethod) throws NotFoundException, CannotCompileException {
if (ctClass.getName().startsWith("com.application.bookstore.entities.test")) {
String testName = ctClass.getName() + "." + ctMethod.getName();
String fileToWrite = "C:/profiler/root.txt";
ctMethod.insertBefore("{ FileWriter fw = new FileWriter(\"" + fileToWrite + "\", true); BufferedWriter out = new BufferedWriter(fw); out.write(\"" + testName + "\"); out.newLine(); out.close(); }");
}
else {
String methodName = ctClass.getName() + "." + ctMethod.getName() + "()";
String fileToRead = "C:/profiler/root.txt";
ctMethod.insertBefore("{ FileReader fr = new FileReader(\"" + fileToRead + "\"); BufferedReader in = new BufferedReader(fr); String line; while((line = in.readLine()) != null); in.close(); FileWriter fw = new FileWriter(line, true); BufferedWriter out = new BufferedWriter(fw); out.write(\"" + methodName + "\"); out.newLine(); out.close(); }");
}
}
/**
* Get current classname and for each methods inside it, call the addInstrumentation method.
*/
@Override
public void onLoad(ClassPool pool, String classname) throws NotFoundException, CannotCompileException {
if (classToImplement(classname))
{
pool.importPackage("java.io");
CtClass ctClass = pool.get(classname);
for (CtMethod ctMethod : ctClass.getDeclaredMethods()) {
if (!Modifier.isNative(ctMethod.getModifiers())) {
addInstrumentation(ctClass, ctMethod);
}
}
}
}
我的问题在其他部分。我无法获得 line 的值,因此打开文件并写入它。
那么,您知道如何检索 line 的值吗?
谢谢