View Javadoc

1   package org.lsst.ccs.utilities.beanutils;
2   
3   import java.util.NoSuchElementException;
4   import java.util.Objects;
5   
6   /**
7    * a Pre-java8 optional class to be replaced by java8 when needed.
8    *
9    * @author bamade
10   */
11  // Date: 09/12/2013
12  
13  public class Optional<T> {
14      private static final Optional<?> EMPTY = new Optional<>();
15  
16      /**
17       * If non-null, the value; if null, indicates no value is present
18       */
19      private final T value;
20  
21      private Optional() {
22          this.value = null;
23      }
24  
25      public static <T> Optional<T> empty() {
26          @SuppressWarnings("unchecked")
27          Optional<T> t = (Optional<T>) EMPTY;
28          return t;
29      }
30  
31      private Optional(T value) {
32          this.value = Objects.requireNonNull(value);
33      }
34  
35      public static <T> Optional<T> of(T value) {
36          return new Optional<>(value);
37      }
38  
39      public static <T> Optional<T> ofNullable(T value) {
40          if (value == null) {
41              return empty();
42          }
43          return of(value);
44      }
45  
46      public T get() {
47          if (value == null) {
48              throw new NoSuchElementException("No value present");
49          }
50          return value;
51      }
52  
53      public boolean isPresent() {
54          return value != null;
55      }
56  
57      public T orElse(T other) {
58          return value != null ? value : other;
59      }
60  
61      @Override
62      public boolean equals(Object obj) {
63          if (this == obj) {
64              return true;
65          }
66  
67          if (!(obj instanceof Optional)) {
68              return false;
69          }
70  
71          Optional<?> other = (Optional<?>) obj;
72          return Objects.equals(value, other.value);
73      }
74  
75      @Override
76      public int hashCode() {
77          return Objects.hashCode(value);
78      }
79  
80  
81      @Override
82      public String toString() {
83          return value != null
84                  ? String.format("Optional[%s]", value)
85                  : "Optional.empty";
86      }
87  
88  
89  }