-
-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathProjected.java
More file actions
62 lines (52 loc) · 1.53 KB
/
Projected.java
File metadata and controls
62 lines (52 loc) · 1.53 KB
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
/*
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import java.util.*;
/**
* A wrapper for a value and its associated {@link Projection}.
*
* @param <T> The value type.
* @author edgar
* @since 4.0.0
*/
public class Projected<T> {
private final T value;
private final Projection<T> projection;
private Projected(T value, Projection<T> projection) {
this.value = value;
this.projection = projection;
}
@SuppressWarnings("unchecked")
public static <T> Projected<T> wrap(T value) {
return new Projected<T>(value, Projection.of(computeProjectionType(value)));
}
@SuppressWarnings("rawtypes")
private static Class computeProjectionType(Object value) {
return switch (value) {
case Set<?> col -> col.isEmpty() ? Object.class : col.iterator().next().getClass();
case Collection<?> col -> col.isEmpty() ? Object.class : col.iterator().next().getClass();
case Optional<?> optional -> optional.isEmpty() ? Object.class : optional.get().getClass();
default -> value.getClass();
};
}
public static <T> Projected<T> wrap(T value, Projection<T> projection) {
return new Projected<>(value, projection);
}
public T getValue() {
return value;
}
public Projection<T> getProjection() {
return projection;
}
public Projected<T> include(String... paths) {
projection.include(paths);
return this;
}
@Override
public String toString() {
return projection.toString();
}
}