Last Updated: February 25, 2016
·
6.676K
· josellarena

Easy, Simple Java Classes ( like Scala case classes, sort of)

Avoid having to write field declarations, toString(), equals() or hashCode() for your classes

  1. Create 2-tuple (pair) class thats generic and overridable:

    public class _<ONE, TWO>
    {
        protected final ONE $1;
        protected final TWO $2;
    
        public _(final ONE _1, final TWO _2)
        {
            this.$1 = _1;
            this.$2 = _2;
        }
    
        public boolean equals(final Object obj)
        {
            return this == obj || obj != null && getClass() == obj.getClass() && $1.equals(((_<?, ?>) obj).$1) && $2.equals(((_<?, ?>) obj).$2);
        }
    
        public int hashCode()
        {
            final int prime = 31;
            int result = 1;
            result = prime * result + ($1 == null ? 0 : $1.hashCode());
            result = prime * result + ($2 == null ? 0 : $2.hashCode());
            return result;
        }
    
        public String toString()
        {
            return format("[%s,%s]",$1,$2);
        }
    
    }
  2. Override with appropriate fields:

    public class Product extends _<String, String>
      {
          public Product(final String id, final String name)
          {
              super(id, name);
          }
    
          public String id()
          {
              return $1;
          }
    
          public String name()
          {
              return $2;
          }
      }
  • You can do the same with singles, triples and quadruples for classes with 1, 3 and 4 fields respectively (beyond 4 it's not worth it). I've found that pairs (ie classes with two dependencies) are by far the most frequent.
  • Improve: check class of fields to optimise hashing function

Inspired by Andy Parker's Equalable

4 Responses
Add your response

What is the benefit?

over 1 year ago ·

The benefit is that you dont have to implement hashCode, equals or toString for new classes, which is one of the (many) reasons java is more verbose than other languages.

over 1 year ago ·

I don't like this method too much, I can suggest you to use Lombok (http://projectlombok.org/) it's a very interesting and useful tool! With it you can have the same (and many others) benefits with a much cleaner code.

over 1 year ago ·

Hi Rascio,

You dont say why you dont like it so not sure how to respond to that. I looked at project lombok and indeed its a terser way of achieving the same effect (thought its scope its larger than this simple trick). The benefit of the approach above is that it is dead simple and under your control, plus you have one less jar dependency to worry about.

over 1 year ago ·