ServiceResolver { @SuppressWarnings("unchecked") public static <T> T getSingletonService(Class<T> intf) { T ret = null; synchronized (singletons) { if (singletons.containsKey(intf)) { ret = (T) singletons.get(intf); } else { List<T> services = getServices(intf); if (!services.isEmpty()) { ret = services.get(0); } singletons.put(intf, ret); } } return ret; }  @SuppressWarnings("unchecked") static T getSingletonService(Class<T> intf); static List<T> getServices(Class<T> intf);  }
@Test public void testSingletonService() { TestService s1 = ServiceResolver.getSingletonService(TestService.class); TestService s2 = ServiceResolver.getSingletonService(TestService.class); assertNotNull(s1); assertNotNull(s2); assertEquals("Should be singleton, so same", s1, s2); }
@Test public void testNoImplementation() { Map<?, ?> s1 = ServiceResolver.getSingletonService(Map.class); assertNull(s1); }