Using the @ToString annotation

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.

Advertisement

3 Responses to Using the @ToString annotation

  1. [...] AnnoJ development Just another WordPress.com weblog « Using the @ToString annotation [...]

  2. [...] to load a class it checks if its methods/fields or the entire class is annotated with @Loggable, @ToString or @Exclude. After that it tries to transform the bytecode of the class according to the [...]

  3. [...] ways of toString() generation with AnnoJ 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 [...]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.