001/* 002 * Copyright (C) 2009 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.collect; 018 019import static com.google.common.base.Preconditions.checkNotNull; 020 021import com.google.common.annotations.GwtIncompatible; 022import com.google.common.primitives.Primitives; 023import com.google.errorprone.annotations.CanIgnoreReturnValue; 024import com.google.errorprone.annotations.DoNotCall; 025import com.google.errorprone.annotations.Immutable; 026import java.io.Serializable; 027import java.util.Map; 028import org.jspecify.annotations.NonNull; 029import org.jspecify.annotations.Nullable; 030 031/** 032 * A {@link ClassToInstanceMap} whose contents will never change, with many other important 033 * properties detailed at {@link ImmutableCollection}. 034 * 035 * @author Kevin Bourrillion 036 * @since 2.0 037 */ 038@Immutable(containerOf = "B") 039@GwtIncompatible 040// TODO(b/278589132): Remove the redundant "@NonNull" on B once it's no longer required by J2KT. 041public final class ImmutableClassToInstanceMap<B> 042 extends ForwardingMap<Class<? extends @NonNull B>, B> 043 implements ClassToInstanceMap<B>, Serializable { 044 045 private static final ImmutableClassToInstanceMap<Object> EMPTY = 046 new ImmutableClassToInstanceMap<>(ImmutableMap.of()); 047 048 /** 049 * Returns an empty {@code ImmutableClassToInstanceMap}. 050 * 051 * <p><b>Performance note:</b> the instance returned is a singleton. 052 * 053 * @since 19.0 054 */ 055 @SuppressWarnings("unchecked") 056 public static <B> ImmutableClassToInstanceMap<B> of() { 057 return (ImmutableClassToInstanceMap<B>) EMPTY; 058 } 059 060 /** 061 * Returns an {@code ImmutableClassToInstanceMap} containing a single entry. 062 * 063 * @since 19.0 064 */ 065 public static <B, T extends B> ImmutableClassToInstanceMap<B> of(Class<T> type, T value) { 066 return new ImmutableClassToInstanceMap<>(ImmutableMap.of(type, value)); 067 } 068 069 /** 070 * Returns a new builder. The generated builder is equivalent to the builder created by the {@link 071 * Builder} constructor. 072 */ 073 public static <B> Builder<B> builder() { 074 return new Builder<>(); 075 } 076 077 /** 078 * A builder for creating immutable class-to-instance maps. Example: 079 * 080 * {@snippet : 081 * static final ImmutableClassToInstanceMap<Handler> HANDLERS = 082 * new ImmutableClassToInstanceMap.Builder<Handler>() 083 * .put(FooHandler.class, new FooHandler()) 084 * .put(BarHandler.class, new SubBarHandler()) 085 * .put(Handler.class, new QuuxHandler()) 086 * .build(); 087 * } 088 * 089 * <p>After invoking {@link #build()} it is still possible to add more entries and build again. 090 * Thus each map generated by this builder will be a superset of any map generated before it. 091 * 092 * @since 2.0 093 */ 094 public static final class Builder<B> { 095 /** Creates a new builder. */ 096 public Builder() {} 097 098 private final ImmutableMap.Builder<Class<? extends B>, B> mapBuilder = ImmutableMap.builder(); 099 100 /** 101 * Associates {@code key} with {@code value} in the built map. Duplicate keys are not allowed, 102 * and will cause {@link #build} to fail. 103 */ 104 @CanIgnoreReturnValue 105 public <T extends B> Builder<B> put(Class<T> key, T value) { 106 mapBuilder.put(key, value); 107 return this; 108 } 109 110 /** 111 * Associates all of {@code map's} keys and values in the built map. Duplicate keys are not 112 * allowed, and will cause {@link #build} to fail. 113 * 114 * @throws NullPointerException if any key or value in {@code map} is null 115 * @throws ClassCastException if any value is not an instance of the type specified by its key 116 */ 117 @CanIgnoreReturnValue 118 public <T extends B> Builder<B> putAll(Map<? extends Class<? extends T>, ? extends T> map) { 119 for (Entry<? extends Class<? extends T>, ? extends T> entry : map.entrySet()) { 120 Class<? extends T> key = entry.getKey(); 121 T value = entry.getValue(); 122 cast(key, value); // If we pass this result to `put` below, it upsets our nullness checker. 123 mapBuilder.put(key, value); 124 } 125 return this; 126 } 127 128 /** 129 * Returns a new immutable class-to-instance map containing the entries provided to this 130 * builder. 131 * 132 * @throws IllegalArgumentException if duplicate keys were added 133 */ 134 public ImmutableClassToInstanceMap<B> build() { 135 ImmutableMap<Class<? extends B>, B> map = mapBuilder.buildOrThrow(); 136 if (map.isEmpty()) { 137 return of(); 138 } else { 139 return new ImmutableClassToInstanceMap<>(map); 140 } 141 } 142 } 143 144 /** 145 * Returns an immutable map containing the same entries as {@code map}. If {@code map} somehow 146 * contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose 147 * comparator is not <i>consistent with equals</i>), the results of this method are undefined. 148 * 149 * <p><b>Note:</b> Despite what the method name suggests, if {@code map} is an {@code 150 * ImmutableClassToInstanceMap}, no copy will actually be performed. 151 * 152 * @throws NullPointerException if any key or value in {@code map} is null 153 * @throws ClassCastException if any value is not an instance of the type specified by its key 154 */ 155 public static <B, S extends B> ImmutableClassToInstanceMap<B> copyOf( 156 Map<? extends Class<? extends S>, ? extends S> map) { 157 if (map instanceof ImmutableClassToInstanceMap) { 158 @SuppressWarnings("rawtypes") // JDT-based J2KT Java frontend does not permit the direct cast 159 Map rawMap = map; 160 @SuppressWarnings("unchecked") // covariant casts safe (unmodifiable) 161 ImmutableClassToInstanceMap<B> cast = (ImmutableClassToInstanceMap<B>) rawMap; 162 return cast; 163 } 164 return new Builder<B>().putAll(map).build(); 165 } 166 167 private final ImmutableMap<Class<? extends B>, B> delegate; 168 169 private ImmutableClassToInstanceMap(ImmutableMap<Class<? extends B>, B> delegate) { 170 this.delegate = delegate; 171 } 172 173 @Override 174 protected Map<Class<? extends B>, B> delegate() { 175 return delegate; 176 } 177 178 @Override 179 public <T extends B> @Nullable T getInstance(Class<T> type) { 180 return cast(type, delegate.get(checkNotNull(type))); 181 } 182 183 /** 184 * Guaranteed to throw an exception and leave the map unmodified. 185 * 186 * @throws UnsupportedOperationException always 187 * @deprecated Unsupported operation. 188 */ 189 @CanIgnoreReturnValue 190 @Deprecated 191 @Override 192 @DoNotCall("Always throws UnsupportedOperationException") 193 public <T extends B> @Nullable T putInstance(Class<T> type, T value) { 194 throw new UnsupportedOperationException(); 195 } 196 197 @CanIgnoreReturnValue 198 private static <T> @Nullable T cast(Class<T> type, @Nullable Object value) { 199 return Primitives.wrap(type).cast(value); 200 } 201 202 Object readResolve() { 203 return isEmpty() ? of() : this; 204 } 205}