Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decorate an object in Java

Tags:

java

decorator

Quick Background

I have a two lists of (large) POJOs being passed in to a method in which I need to ensure uniqueness across the two lists. The best solution I can see is construct two sets and check that their intersection is empty.

The Problem

For the context of this method, and this method alone, I need to override the equals and hashcode method of the POJOs in question.

What I Am Looking For

This seems like a prime candiate to decorate the existing objects. I have looked at Guava's ForwardingObject but it seems best suited for delegating objects that implement a given interface which is not my case. In general, I am looking for a solution that ...

  1. Avoids coping all of the fields in the large POJO (copy constructors).
  2. Easy to understand and maintain
  3. Avoids creating a whole new class that extends the POJO for the sake of this one method
like image 228
Andrew White Avatar asked Jan 26 '11 16:01

Andrew White


1 Answers

I'd just go with a wrapper class.

Create a new class that is instantiated with your POJO in the constructor. It doesn't copy the POJO, just holds onto the reference to the original. Then write equals and hashcode however you like in that wrapper class.

Something like this:

public class MySpecialWrapper{
  private final BigPojo delegate;

  public MySpecialWrapper(BigPojo pojo){
    this.delegate = pojo;
  }

  public int hashCode(){
    //insert special impl here.
  }

  public boolean equals(Object o){
    //insert special impl here.
  }
}

Put instances of the wrapper class into your Sets and use that for uniqueness verification. Add an accessor method (getDelegate) if you need to get access to the offending POJO in the case of a failure.

like image 139
rfeak Avatar answered Sep 28 '22 04:09

rfeak