Basic.java revision 16177:89ef4b822745
1/* 2 * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24// 25 26import java.io.*; 27import java.util.*; 28 29 30public class Basic { 31 32 private static PrintStream out = System.err; 33 34 private static <T> Set<T> setOf(Iterable<T> it) { 35 Set<T> s = new HashSet<T>(); 36 for (T t : it) 37 s.add(t); 38 return s; 39 } 40 41 private static <T> void checkEquals(Set<T> s1, Set<T> s2, boolean eq) { 42 if (s1.equals(s2) != eq) 43 throw new RuntimeException(String.format("%b %s : %s", 44 eq, s1, s2)); 45 } 46 47 abstract static class TestLoader { 48 String name; 49 50 TestLoader(String name) { this.name = name; } 51 52 abstract ServiceLoader<FooService> load(); 53 } 54 55 static TestLoader tcclLoader = new TestLoader("Thread context class loader") { 56 ServiceLoader<FooService> load() { 57 return ServiceLoader.load(FooService.class); 58 } 59 }; 60 61 static TestLoader systemClLoader = new TestLoader("System class loader") { 62 ServiceLoader<FooService> load() { 63 return ServiceLoader.load(FooService.class, ClassLoader.getSystemClassLoader()); 64 } 65 }; 66 67 static TestLoader nullClLoader = new TestLoader("null (defer to system class loader)") { 68 ServiceLoader<FooService> load() { 69 return ServiceLoader.load(FooService.class, null); 70 } 71 }; 72 73 public static void main(String[] args) { 74 for (TestLoader tl : Arrays.asList(tcclLoader, systemClLoader, nullClLoader)) { 75 test(tl); 76 } 77 } 78 79 static void test(TestLoader tl) { 80 ServiceLoader<FooService> sl = tl.load(); 81 out.format("%s: %s%n", tl.name, sl); 82 83 // Providers are cached 84 Set<FooService> ps = setOf(sl); 85 checkEquals(ps, setOf(sl), true); 86 87 // The cache can be flushed and reloaded 88 sl.reload(); 89 checkEquals(ps, setOf(sl), false); 90 91 } 92} 93