Inserting code at runtime using Javassist byte-code editorFollowing code shows how to insert code dynamically before loading its class: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.prismoskills</groupId> <artifactId>javassist-examples</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>jar</packaging> <name>javassist-examples</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.18.1-GA</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> </dependencies> </project> package com.prismoskills.javassist.examples.annotation; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; /** * Example showing how to dynamically insert code using Javassist byte-code editor */ public class DynamicCodeInsertion { static String pkgName = "com.prismoskills.javassist.examples.annotation"; public static void main(String[] args) throws Exception { ClassPool cp = ClassPool.getDefault(); CtClass cc = cp.get(pkgName + ".FooCodeInsertion"); // Without the call to "makePackage()", package information is lost cp.makePackage(cp.getClassLoader(), pkgName); CtMethod m = cc.getDeclaredMethod("helloWorld"); m.insertBefore("{System.out.print(\"Oh, say no to \");}"); m.insertAfter("{System.out.print(\"And say - Hi World\");}"); // Changes are not persisted without a call to "toClass()" cc.toClass(); (new FooCodeInsertion()).helloWorld(); } } class FooCodeInsertion { public void helloWorld () { System.out.println ("Hello World"); } } Output for the above is: Oh, say no to Hello World And say - Hi World |
Got a thought to share or found a
bug in the code?
We'd love to hear from you:
Name: | |
Email: | (Your email is not shared with anybody) |
Comment: |
Facebook comments: