Alternative ways of toString() generation with AnnoJ

October 15, 2009

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.


How to use AnnoJ?

October 14, 2009

As I mentioned in the previous post in AnnoJ everything’s implemented with annotations. More precisely: with runtime annotations. This means that you can place annotations on your packages (I will explain how), classes, methods and fields and these are evaluated at runtime. In the current version of AnnoJ the problem of runtime annotation evaluation is solved with the use of a custom classloader. You must load all your annotated classes with this classloader. To make this task easy AnnoJ defines the MainMethodBootstrap class. This class is responsible for the corrent processing of the annotations. The only thing you have to do is to tell it the name of the main class of your application and the command-line arguments you want to pass. An example:

 public class StarterClass{

		public static void main(String[] args){
			MainMethodBootstrap.callMainMethod("ClassWithMainMethod",
						 new String[]{"something"});
		}
	}

Here ClassWithMainMethod is the main class (ie. contains a public static void main(String[]) method).The command-line arguments to be passed to the main method are listed in the second argument of the callMainMethod() method. And that’s all!

One important thing is that because of the custom classloader at the moment AnnoJ can’t be used in application servers. Hopefully this will change in the future versions.


Follow

Get every new post delivered to your Inbox.