Tuesday, December 13, 2005

Null Placeholders in JDK 1.5

Null placeholders come in handy when you want to support null values but a Map implementation you depend on doesn't. An enum placeholder maintains object identity across object serialization for free:
  enum Null { VALUE }

  /**
   * Replaces null with placeholder.
   */
  Object replaceNull(Object value) {
    return value == null ? Null.VALUE : value;
  }

  /**
   * Resolves placeholder as null.
   */
  Object resolveNull(Object value) {
    return value == Null.VALUE ? null : value;
  }
Things can still get a little hairy when you mix null placeholders with generic types. Your placeholder can implement the same type as the value, or you can resort to casting hacks.

0 Comments:

Post a Comment

<< Home