Friday, September 16, 2016

Java 8 equals helper using lambda expression

public class Equals {
 private Equals() {}

 public static  boolean of(Class type, Object obj, Predicate pred) {
  if (obj == null) {
   return false;
  }
  if (!type.isInstance(obj)) {
   return false;
  }
  T other = type.cast(obj);
  return pred.test(other);
 }
}
Usage example:
@Override
public boolean equals(Object obj) {
 return Equals.of(ClassKey.class, obj, other -> 
   Objects.equals(this.kind, other.kind) &&
   Objects.equals(this.obj, other.obj)
  );
}