package com.zuozewei.javaagent01;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
public class ClassFileTransformerDemo implements ClassFileTransformer {
public byte[] transform(ClassLoader loader, String className, Class> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {
System.out.println("className: " + className);
if (!className.equalsIgnoreCase("com/zuozewei/Dog")) {
return null;
}
return getBytesFromFile("/Users/zuozewei/IdeaProjects/javaagent/example01/target/classes/com/zuozewei/Dog.class");
}
public static byte[] getBytesFromFile(String fileName) {
File file = new File(fileName);
try (InputStream is = new FileInputStream(file)) {
// precondition
long length = file.length();
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset = 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
is.close();
return bytes;
} catch (Exception e) {
System.out.println("error occurs in _ClassTransformer!"
+ e.getClass().getName());
return null;
}
}
}
5、定义需要修改的项目 example01
6、实现需要修改的类的。
main:
package com.zuozewei;
public class Main {
public static void main(String[] args) {
System.out.println("7DGroup");
System.out.println(new Dog().hello());
// System.out.println(new Cat().hello());
}
}
Dog:
package com.zuozewei;
public class Dog {
public int hello() {
return 0;
}
}
7、运行 example01 的 main 方法:
8、打包 javaagent 项目生成 jar 文件,并将 java 文件同 example01 项目的 jar 放在同一个目录下如上图(放在同一个目录为了方便执行)