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.


Using the @ToString annotation

October 14, 2009

One of the annotation types of AnnoJ is @ToString. With @ToString you can leave the implementation of the toString() methods to AnnoJ. After bootstrapping your application you can use toString() as if you implemented it manually.

To generate the toString() method in a class simply put the @ToString annotation just before the class definition:


@ToString
	public class InterestingClass{
		private Integer x;
                private String s;
                // more code
	}

After bootstrapping the application AnnoJ will generate a toString() method similar to this:


public String toString(){

return "[" + (this.x==null?"":"x="+this.x) + "," + (this.s==null?"":"s="+this.s) + "]";

}

If you want to leave x from the method just place the @Exclude annotation before the field:


@ToString
	public class InterestingClass{
                @Exclude
		private Integer x;
                private String s;
                // more code
	}

To generate a toString() method in all classes of a package you should define a public class named PackageInfo and annotate it with @ToString:


@ToString public class PackageInfo{}

In the future versions of AnnoJ there will be an option to leave out from toString() generation all fields with a given visiblity and you will be able to use the @Include annotation together with @ToString.


Follow

Get every new post delivered to your Inbox.