/
ImmutableClassToInstanceMap.java
205 lines (185 loc) · 7.1 KB
/
ImmutableClassToInstanceMap.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.primitives.Primitives;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.Map;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* A {@link ClassToInstanceMap} whose contents will never change, with many other important
* properties detailed at {@link ImmutableCollection}.
*
* @author Kevin Bourrillion
* @since 2.0
*/
@Immutable(containerOf = "B")
@GwtIncompatible
@ElementTypesAreNonnullByDefault
// TODO(b/278589132): Remove the redundant "@NonNull" on B once it's no longer required by J2KT.
public final class ImmutableClassToInstanceMap<B>
extends ForwardingMap<Class<? extends @NonNull B>, B>
implements ClassToInstanceMap<B>, Serializable {
private static final ImmutableClassToInstanceMap<Object> EMPTY =
new ImmutableClassToInstanceMap<>(ImmutableMap.<Class<?>, Object>of());
/**
* Returns an empty {@code ImmutableClassToInstanceMap}.
*
* <p><b>Performance note:</b> the instance returned is a singleton.
*
* @since 19.0
*/
@SuppressWarnings("unchecked")
public static <B> ImmutableClassToInstanceMap<B> of() {
return (ImmutableClassToInstanceMap<B>) EMPTY;
}
/**
* Returns an {@code ImmutableClassToInstanceMap} containing a single entry.
*
* @since 19.0
*/
public static <B, T extends B> ImmutableClassToInstanceMap<B> of(Class<T> type, T value) {
ImmutableMap<Class<? extends B>, B> map = ImmutableMap.<Class<? extends B>, B>of(type, value);
return new ImmutableClassToInstanceMap<>(map);
}
/**
* Returns a new builder. The generated builder is equivalent to the builder created by the {@link
* Builder} constructor.
*/
public static <B> Builder<B> builder() {
return new Builder<>();
}
/**
* A builder for creating immutable class-to-instance maps. Example:
*
* <pre>{@code
* static final ImmutableClassToInstanceMap<Handler> HANDLERS =
* new ImmutableClassToInstanceMap.Builder<Handler>()
* .put(FooHandler.class, new FooHandler())
* .put(BarHandler.class, new SubBarHandler())
* .put(Handler.class, new QuuxHandler())
* .build();
* }</pre>
*
* <p>After invoking {@link #build()} it is still possible to add more entries and build again.
* Thus each map generated by this builder will be a superset of any map generated before it.
*
* @since 2.0
*/
public static final class Builder<B> {
private final ImmutableMap.Builder<Class<? extends B>, B> mapBuilder = ImmutableMap.builder();
/**
* Associates {@code key} with {@code value} in the built map. Duplicate keys are not allowed,
* and will cause {@link #build} to fail.
*/
@CanIgnoreReturnValue
public <T extends B> Builder<B> put(Class<T> key, T value) {
mapBuilder.put(key, value);
return this;
}
/**
* Associates all of {@code map's} keys and values in the built map. Duplicate keys are not
* allowed, and will cause {@link #build} to fail.
*
* @throws NullPointerException if any key or value in {@code map} is null
* @throws ClassCastException if any value is not an instance of the type specified by its key
*/
@CanIgnoreReturnValue
public <T extends B> Builder<B> putAll(Map<? extends Class<? extends T>, ? extends T> map) {
for (Entry<? extends Class<? extends T>, ? extends T> entry : map.entrySet()) {
Class<? extends T> type = entry.getKey();
T value = entry.getValue();
mapBuilder.put(type, cast(type, value));
}
return this;
}
private static <T> T cast(Class<T> type, Object value) {
return Primitives.wrap(type).cast(value);
}
/**
* Returns a new immutable class-to-instance map containing the entries provided to this
* builder.
*
* @throws IllegalArgumentException if duplicate keys were added
*/
public ImmutableClassToInstanceMap<B> build() {
ImmutableMap<Class<? extends B>, B> map = mapBuilder.buildOrThrow();
if (map.isEmpty()) {
return of();
} else {
return new ImmutableClassToInstanceMap<>(map);
}
}
}
/**
* Returns an immutable map containing the same entries as {@code map}. If {@code map} somehow
* contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose
* comparator is not <i>consistent with equals</i>), the results of this method are undefined.
*
* <p><b>Note:</b> Despite what the method name suggests, if {@code map} is an {@code
* ImmutableClassToInstanceMap}, no copy will actually be performed.
*
* @throws NullPointerException if any key or value in {@code map} is null
* @throws ClassCastException if any value is not an instance of the type specified by its key
*/
public static <B, S extends B> ImmutableClassToInstanceMap<B> copyOf(
Map<? extends Class<? extends S>, ? extends S> map) {
if (map instanceof ImmutableClassToInstanceMap) {
@SuppressWarnings("rawtypes") // JDT-based J2KT Java frontend does not permit the direct cast
Map rawMap = map;
@SuppressWarnings("unchecked") // covariant casts safe (unmodifiable)
ImmutableClassToInstanceMap<B> cast = (ImmutableClassToInstanceMap<B>) rawMap;
return cast;
}
return new Builder<B>().putAll(map).build();
}
private final ImmutableMap<Class<? extends B>, B> delegate;
private ImmutableClassToInstanceMap(ImmutableMap<Class<? extends B>, B> delegate) {
this.delegate = delegate;
}
@Override
protected Map<Class<? extends B>, B> delegate() {
return delegate;
}
@Override
@SuppressWarnings("unchecked") // value could not get in if not a T
@CheckForNull
public <T extends B> T getInstance(Class<T> type) {
return (T) delegate.get(checkNotNull(type));
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
@CheckForNull
public <T extends B> T putInstance(Class<T> type, T value) {
throw new UnsupportedOperationException();
}
Object readResolve() {
return isEmpty() ? of() : this;
}
}