@ SuppressWarnings ( "unchecked" ) private static < S > Iterable < S > constructAllServiceImplementations ( Class < S > _service ) { ClassLoader cl = CacheManagerImpl . class . getClassLoader ( ) ; ArrayList < S > li = new ArrayList < S > ( ) ; Iterator < S > it = ServiceLoader . load ( _service , cl ) . iterator ( ) ; while ( it . hasNext ( ) ) { try { li . add ( it . next ( ) ) ; } catch ( ServiceConfigurationError ex ) { Log . getLog ( CacheManager . class . getName ( ) ) . debug ( "Error loading service '" + _service + "'" , ex ) ; } } final S [ ] a = ( S [ ] ) Array . newInstance ( _service , li . size ( ) ) ; li . toArray ( a ) ; return new Iterable < S > ( ) { public Iterator < S > iterator ( ) { return new Iterator < S > ( ) { private int pos = 0 ; public boolean hasNext ( ) { return pos < a . length ; } public S next ( ) { return a [ pos ++ ] ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } } ; }
The service loader works lazy however we want to have all implementations constructed . Retrieve all implementations from the service loader and return an read - only iterable backed by an array .