javassist初接触
直接上代码:
pom增加依赖:
<dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.18.2-GA</version> </dependency>
写个Hello类:
package JavassistTest.JavassistTest; public class Hello { public void sayHello(){ System.out.println("Hello world"); } }
主类:
package JavassistTest.JavassistTest; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.NotFoundException; /** * Hello world! * */ public class App { public static void main(String[] args) throws NotFoundException, CannotCompileException, InstantiationException, IllegalAccessException, ClassNotFoundException { //~加上报错,和类加载有关系,这里new的话会把Hello类加载,之后再加载的话就会报错 //Hello hell=new Hello(); //hell.sayHello(); //~ CtClass ctClass = ClassPool.getDefault().getCtClass("JavassistTest.JavassistTest.Hello"); CtMethod ctMethod = ctClass.getDeclaredMethod("sayHello"); ctMethod.setBody("System.out.println(\"hi\");"); Class ch=ctClass.toClass(); Hello h=(Hello) ch.newInstance(); h.sayHello(); Hello hel=new Hello(); hel.sayHello();
} }
输出结果:
hi
hi
结果一样,说明是class被修改了。