@Test public void putAndGetInstance() { // given ClassToInstanceMap<Exception> map = MutableClassToInstanceMap.create(); // when map.putInstance(RuntimeException.class, new RuntimeException()); map.putInstance(NullPointerException.class, new NullPointerException()); // then assertThat(map.getInstance(RuntimeException.class), is(RuntimeException.class)); assertThat(map.getInstance(NullPointerException.class), is(NullPointerException.class)); }
/** * Returns an arbitrary instance for {@code type}, or {@code null} if no arbitrary instance can be * determined. */ @Nullable public static <T> T get(Class<T> type) { T defaultValue = DEFAULTS.getInstance(type); if (defaultValue != null) { return defaultValue; } Class<? extends T> implementation = getImplementation(type); if (implementation != null) { return get(implementation); } if (type.isEnum()) { T[] enumConstants = type.getEnumConstants(); return (enumConstants.length == 0) ? null : enumConstants[0]; } if (type.isArray()) { return createEmptyArray(type); } T jvmDefault = Defaults.defaultValue(Primitives.unwrap(type)); if (jvmDefault != null) { return jvmDefault; } if (Modifier.isAbstract(type.getModifiers()) || !Modifier.isPublic(type.getModifiers())) { return arbitraryConstantInstanceOrNull(type); } final Constructor<T> constructor; try { constructor = type.getConstructor(); } catch (NoSuchMethodException e) { return arbitraryConstantInstanceOrNull(type); } constructor.setAccessible(true); // accessibility check is too slow try { return constructor.newInstance(); } catch (InstantiationException impossible) { throw new AssertionError(impossible); } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); } catch (InvocationTargetException e) { logger.log(Level.WARNING, "Exception while invoking default constructor.", e.getCause()); return arbitraryConstantInstanceOrNull(type); } }
@Override protected RpcConsumerRegistry createInstance( final BindingToNormalizedNodeCodec codec, final ClassToInstanceMap<DOMService> delegates) { final DOMRpcService domRpc = delegates.getInstance(DOMRpcService.class); return new BindingDOMRpcServiceAdapter(domRpc, codec); }
@Override protected DataBroker createInstance( final BindingToNormalizedNodeCodec codec, final ClassToInstanceMap<DOMService> delegates) { final DOMDataBroker domDataBroker = delegates.getInstance(DOMDataBroker.class); return new BindingDOMDataBrokerAdapter(domDataBroker, codec); }
protected <T extends BrokerService> Optional<T> getGlobalService(final Class<T> service) { return Optional.fromNullable(services.getInstance(service)); }