AnnotationHandlers { @SuppressWarnings({"unchecked", "ConstantConditions"}) @Nullable public static <T extends AnnotationHandler> T obtainHandler(@NonNull final Class<T> classOfHandler, @NonNull final Class<?> annotatedClass) { Object handler = null; if (FragmentAnnotations.isEnabled()) { synchronized (LOCK) { if (handlers == null) { handlers = new HashMap<>(HANDLERS_INITIAL_CAPACITY); } handler = handlers.get(annotatedClass); if (handler == null) { handler = instantiateHandler(classOfHandler, annotatedClass); handlers.put(annotatedClass, handler); } else if (!handler.getClass().equals(classOfHandler)) { final String newHandlerName = classOfHandler.getSimpleName(); final String currentHandlerName = handler.getClass().getSimpleName(); final String className = annotatedClass.getSimpleName(); throw new ClassCastException( "Trying to obtain handler(" + newHandlerName + ") for class(" + className + ") while there " + "is already handler(" + currentHandlerName + ") of different type for that class!" ); } } } return (T) handler; } AnnotationHandlers(); @SuppressWarnings({"unchecked", "ConstantConditions"}) @Nullable static T obtainHandler(@NonNull final Class<T> classOfHandler, @NonNull final Class<?> annotatedClass);  }
@SuppressWarnings("ConstantConditions") @Test public void testObtainHandler() { final Handler handler = AnnotationHandlers.obtainHandler(Handler.class, AnnotatedComponent.class); assertThat(handler, is(notNullValue())); assertSame(handler.getAnnotatedClass(), AnnotatedComponent.class); }
@Test(expected = IllegalStateException.class) public void testObtainHandlerThatIsAbstract() { AnnotationHandlers.obtainHandler(AbstractHandler.class, AnnotatedComponent.class); }
@Test(expected = IllegalStateException.class) public void testObtainHandlerWithPrivateConstructor() { AnnotationHandlers.obtainHandler(PrivateHandler.class, AnnotatedComponent.class); }
@Test public void testObtainHandlerAlreadyInstantiated() { final Handler handler = AnnotationHandlers.obtainHandler(Handler.class, AnnotatedComponent.class); assertThat(handler, is(AnnotationHandlers.obtainHandler(Handler.class, AnnotatedComponent.class))); }
@Test(expected = ClassCastException.class) public void testObtainHandlerOfDifferentType() { AnnotationHandlers.obtainHandler(Handler.class, AnnotatedComponent.class); AnnotationHandlers.obtainHandler(SecondHandler.class, AnnotatedComponent.class); }
@Test public void testObtainHandlerWhenAnnotationsAreDisabled() { FragmentAnnotations.setEnabled(false); assertThat(AnnotationHandlers.obtainHandler(Handler.class, AnnotatedComponent.class), is(nullValue())); FragmentAnnotations.setEnabled(true); }