Path: blob/master/test/jdk/java/util/ServiceLoader/basic/Basic.java
41153 views
/*1* Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223//2425import java.io.*;26import java.util.*;272829public class Basic {3031private static PrintStream out = System.err;3233private static <T> Set<T> setOf(Iterable<T> it) {34Set<T> s = new HashSet<T>();35for (T t : it)36s.add(t);37return s;38}3940private static <T> void checkEquals(Set<T> s1, Set<T> s2, boolean eq) {41if (s1.equals(s2) != eq)42throw new RuntimeException(String.format("%b %s : %s",43eq, s1, s2));44}4546abstract static class TestLoader {47String name;4849TestLoader(String name) { this.name = name; }5051abstract ServiceLoader<FooService> load();52}5354static TestLoader tcclLoader = new TestLoader("Thread context class loader") {55ServiceLoader<FooService> load() {56return ServiceLoader.load(FooService.class);57}58};5960static TestLoader systemClLoader = new TestLoader("System class loader") {61ServiceLoader<FooService> load() {62return ServiceLoader.load(FooService.class, ClassLoader.getSystemClassLoader());63}64};6566static TestLoader nullClLoader = new TestLoader("null (defer to system class loader)") {67ServiceLoader<FooService> load() {68return ServiceLoader.load(FooService.class, null);69}70};7172public static void main(String[] args) {73for (TestLoader tl : Arrays.asList(tcclLoader, systemClLoader, nullClLoader)) {74test(tl);75}76}7778static void test(TestLoader tl) {79ServiceLoader<FooService> sl = tl.load();80out.format("%s: %s%n", tl.name, sl);8182// Providers are cached83Set<FooService> ps = setOf(sl);84checkEquals(ps, setOf(sl), true);8586// The cache can be flushed and reloaded87sl.reload();88checkEquals(ps, setOf(sl), false);8990}91}929394