mkarneim / pojobuilder

A Java Code Generator for Pojo Builders
Other
334 stars 44 forks source link

Use sneaky-throws in clone() method #161

Open drekbour opened 5 years ago

drekbour commented 5 years ago

Currently PB clone() wraps the (checked) CloneNotSupportedException with InternalError. As of Java 8, the following "sneaky throws" allows the code to propagate the checked exception directly.

  @Override
  @GwtIncompatible
  public Object clone() {
    return _clone();
  }

  private <T extends Throwable> Object _clone() throws T {
    try {
      BookBuilder result = (BookBuilder)super.clone();
      result.self = result;
      return result;
    } catch (CloneNotSupportedException e) {
      throw (T)e; // "Sneaky-throws" CloneNotSupportedException
    }
  }

It's also worth discussing if clone() should be suppressing at all. It's fine for but() to do this but I don't follow why we're trying to reduce the public method.