您需要的是构建时或编译时仪器,而不是运行时。大多数字节码检测工具都支持 - Javassist,AspectJ,ASM。
实际上,您可以将由您的代理程序检测的字节码保存到.class
文件,其结果只是表示类的字节数组。但是,您必须至少与代理程序一起运行您的程序,并确保您加载了所有需要仪器的类,以便为每个类创建一个.class
文件。所以我不推荐这种方法。
if (shouldInstrument) {
CtClass cclass = pool.get(className.replaceAll("/", "."));
// Instrument the class here
byte[] bytecode = cclass.toBytecode();
File outputFile = new File(String.format("%s/%s.class", outputDirectory, className));
Files.createDirectories(outputFile.getParentFile().toPath());
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
fos.write(bytecode);
}
return bytecode;
}
另外,如果你的目标是不污染的源代码与样板代码一些功能添加到您自己的类,你可以操纵的源代码,而不是字节码。源 - >生成源 - >字节码(编译)。例如,使用注释和自定义annotation processor。
你正在仪表自己的班级或第三方图书馆? – vempo
@vempo我自己的类,示例代码与可用的源代码。 – Qoros