javassist-maven-plugin icon indicating copy to clipboard operation
javassist-maven-plugin copied to clipboard

Maven plugin that will apply Javassist bytecode transformations during build time.

h1. Javassist Maven Plugin

p.

p. A simple Maven plugin that can apply Javassist tranformation on classes after compilation.

h2. How to use it

p. Include the plugin on your @pom.xml@ descriptor:

bc.. <groupId>de.icongmbh.oss.maven.plugins</groupId> <artifactId>javassist-maven-plugin</artifactId> 2.0.2 <includeTestClasses>false</includeTestClasses> <transformerClasses> <transformerClass> <className>com.domain.ToStringTransformer</className> append.value and ToStringTransformer </transformerClass> </transformerClasses> process-classes javassist

p. You must implement Class transformers, here's one simple example (at least, not a "logger" one).

bc.. /**

  • Silly transformer, used to hack the toString method. */ public class ToStringTransformer extends ClassTransformer {

private static final String APPEND_VALUE_PROPERTY_KEY = "append.value";

private String appendValue;

/**

  • We'll only transform subtypes of MyInterface. */ @Override public boolean shouldTransform(final CtClass candidateClass) throws JavassistBuildException { CtClass myInterface = ClassPool.getDefault().get(MyInterface.class.getName()); try { return !candidateClass.equals(myInterface) && candidateClass.subtypeOf(myInterface); } catch (NotFoundException e) { throw new JavassistBuildException(e); } }

/**

  • Hack the toString() method. */ @Override public void applyTransformations(CtClass classToTransform) throws JavassistBuildException { try { // Actually you must test if it exists, but it's just an example... CtMethod toStringMethod = classToTransform.getDeclaredMethod("toString"); classToTransform.removeMethod(toStringMethod);

    CtMethod hackedToStringMethod = CtNewMethod .make("public String toString() { return "toString() hacked by Javassist" + ( this.appendValue != null ? this.appendValue : "") + ""; }", classToTransform); classToTransform.addMethod(hackedToStringMethod); } catch (CannotCompileException | NotFoundException e) { throw new JavassistBuildException(e); } }

@Override public void configure(final Properties properties) { if (null == properties) { return; } this.appendValue = properties.getProperty(APPEND_VALUE_PROPERTY_KEY); } }

h2. Known limitations

  • Don't instrument classes inside .jar files, only classes on your project;
  • Lack of unit tests and sample app;
  • Further implementations of @de.icongmbh.oss.maven.plugin.javassist.ClassTransformer@ can enable easier interactions with the Javassist API (provide some utilities).

h2. How to contribute?

p. If you think this project is useful for you, then there's a huge chance it's useful to others, so please feel free to fork, fix it, improve it and test it (the "Known limitations" above is a great way to start).

h2. Documentation