-
Notifications
You must be signed in to change notification settings - Fork 30
/
JsonNullable.java
111 lines (92 loc) · 2.94 KB
/
JsonNullable.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package org.openapitools.jackson.nullable;
import java.io.Serializable;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Consumer;
public class JsonNullable<T> implements Serializable {
private static final long serialVersionUID = 1L;
private static final JsonNullable<?> UNDEFINED = new JsonNullable<>(null, false);
private final T value;
private final boolean isPresent;
private JsonNullable(T value, boolean isPresent) {
this.value = value;
this.isPresent = isPresent;
}
/**
* Create a <code>JsonNullable</code> representing an undefined value (not present).
*
* @param <T> a type wildcard
* @return an empty <code>JsonNullable</code> with no value defined
*/
public static <T> JsonNullable<T> undefined() {
@SuppressWarnings("unchecked")
JsonNullable<T> t = (JsonNullable<T>) UNDEFINED;
return t;
}
/**
* Create a <code>JsonNullable</code> from the submitted value.
*
* @param value the value
* @param <T> the type of the value
* @return the <code>JsonNullable</code> with the submitted value present.
*/
public static <T> JsonNullable<T> of(T value) {
return new JsonNullable<>(value, true);
}
/**
* Obtain the value of this <code>JsonNullable</code>.
*
* @return the value, if present
* @throws NoSuchElementException if no value is present
*/
public T get() {
if (!isPresent) {
throw new NoSuchElementException("Value is undefined");
}
return value;
}
/**
* Obtain the value of this <code>JsonNullable</code>.
*
* @param other the value to be returned if no value is present
* @return the value of this <code>JsonNullable</code> if present, the submitted value otherwise
*/
public T orElse(T other) {
return this.isPresent ? this.value : other;
}
public boolean isPresent() {
return isPresent;
}
/**
* If a value is present, performs the given action with the value,
* otherwise does nothing.
*
* @param action the action to be performed, if a value is present
*/
public void ifPresent(
Consumer<? super T> action) {
if (this.isPresent) {
action.accept(value);
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof JsonNullable)) {
return false;
}
JsonNullable<?> other = (JsonNullable<?>) obj;
return Objects.equals(value, other.value) &&
isPresent == other.isPresent;
}
@Override
public int hashCode() {
return Objects.hash(value, isPresent);
}
@Override
public String toString() {
return this.isPresent ? String.format("JsonNullable[%s]", value) : "JsonNullable.undefined";
}
}