import javassist.*; public class JavassistExample { public static void main(String[] args) throws Exception { ClassPool pool = ClassPool.getDefault(); CtClass ctClass = pool.get("com.example.MyClass"); CtMethod newMethod = CtNewMethod.make("public void newMethod() { System.out.println(\"Hello, Javassist!\"); }", ctClass); ctClass.addMethod(newMethod); CtMethod existingMethod = ctClass.getDeclaredMethod("existingMethod"); existingMethod.insertBefore("System.out.println(\"Before existingMethod\");"); Class<?> modifiedClass = ctClass.toClass(); Object obj = modifiedClass.newInstance(); obj.getClass().getMethod("newMethod").invoke(obj); obj.getClass().getMethod("existingMethod").invoke(obj); } }


上一篇:
下一篇:
切换中文