In the post “Using the @ToString annotation” you saw how easy it is to use @ToString
. In this post I’ll show you how you can generate toString()
methods in classes without using MainMethodBootstrap
.
The annoj.annotation.transformers
package contains classes that are responsible for transforming class bytecode. Currently there’s one for toString()
generation and onew for logging. In order to be able to instrument classes you have to instantiate TransformingClassLoader
with a list of ClassTransformer
objects and use that instance for loading the classes you want to modify. For example:
List tl = Collections.singletonList(new ToStringCreator()); TransformingClassLoader loader = new TransformingClassLoader(tl); loader.loadClass("Person");
This classloader modifies the classes if it finds the appropriate annotations. It’s important that the classloader should only be used in a so called bootstrap class which loads this classloader and then loads the classes with it.