/** * "Smart" registry just for this particular {@code type}. It is typically composed with existing * registries using {@link org.bson.codecs.configuration.CodecRegistries#fromRegistries(CodecRegistry...)} method. */ public static <T> CodecRegistry registryFor(final Class<T> type, final TypeAdapter<T> adapter) { return new CodecRegistry() { @SuppressWarnings("unchecked") @Override public <X> Codec<X> get(Class<X> clazz) { // TODO is this a safe assumption with polymorphism (in repositories) ? if (type.isAssignableFrom(clazz)) { return (Codec<X>) codecFor(type, adapter); } else { // let other registries decide throw new CodecConfigurationException(String.format("Type %s not supported by this registry", type.getName())); } } }; }
private <V> Codec<V> getCodecForType(Class<V> fieldType) { if (ignoredTypes.contains(fieldType)) { return null; } try { return registry.get(fieldType); } catch (CodecConfigurationException | MongoMapperException e) { // No other way to check without catching exception. // Cache types without codec to improve performance ignoredTypes.add(fieldType); } return null; }
/** * "Smart" registry just for this particular {@code type}. It is typically composed with existing * registries using {@link org.bson.codecs.configuration.CodecRegistries#fromRegistries(CodecRegistry...)} method. */ public static <T> CodecRegistry registryFor(final Class<T> type, final TypeAdapter<T> adapter) { return new CodecRegistry() { @SuppressWarnings("unchecked") @Override public <X> Codec<X> get(Class<X> clazz) { // TODO is this a safe assumption with polymorphism (in repositories) ? if (type.isAssignableFrom(clazz)) { return (Codec<X>) codecFor(type, adapter); } // let other registries decide throw new CodecConfigurationException(String.format("Type %s not supported by this registry", type.getName())); } }; }
@Test(expected = CodecConfigurationException.class) public void testOneProviderWithNotExistingCodec() { OneProvider provider = new OneProvider(); CodecRegistry codecRegistry = CodecRegistries.fromProviders(provider); assertThat(codecRegistry.get(TwoPojo.class)).isNull(); }