您需要的是構建時或編譯時儀器,而不是運行時。大多數字節碼檢測工具都支持 - 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