PageRenderTime 79ms CodeModel.GetById 30ms RepoModel.GetById 2ms app.codeStats 0ms

/src/main/java/com/alibaba/fastjson/util/ServiceLoader.java

https://bitbucket.org/xiejuntao/xdesktop
Java | 89 lines | 73 code | 14 blank | 2 comment | 11 complexity | 20107e50a260b02945dab7be495eb040 MD5 | raw file
  1. package com.alibaba.fastjson.util;
  2. import java.io.BufferedReader;
  3. import java.io.Closeable;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.net.URL;
  8. import java.util.Enumeration;
  9. import java.util.HashSet;
  10. import java.util.Set;
  11. public class ServiceLoader {
  12. private static final String PREFIX = "META-INF/services/";
  13. private static final Set<String> loadedUrls = new HashSet<String>();
  14. @SuppressWarnings("unchecked")
  15. public static <T> Set<T> load(Class<T> clazz, ClassLoader classLoader) {
  16. Set<T> services = new HashSet<T>();
  17. String className = clazz.getName();
  18. String path = PREFIX + className;
  19. Set<String> serviceNames = new HashSet<String>();
  20. try {
  21. Enumeration<URL> urls = classLoader.getResources(path);
  22. while (urls.hasMoreElements()) {
  23. URL url = urls.nextElement();
  24. if (loadedUrls.contains(url.toString())) {
  25. continue;
  26. }
  27. load(url, serviceNames);
  28. loadedUrls.add(url.toString());
  29. }
  30. } catch (IOException ex) {
  31. // skip
  32. }
  33. for (String serviceName : serviceNames) {
  34. try {
  35. Class<?> serviceClass = classLoader.loadClass(serviceName);
  36. T service = (T) serviceClass.newInstance();
  37. services.add(service);
  38. } catch (Exception e) {
  39. // skip
  40. }
  41. }
  42. return services;
  43. }
  44. public static void load(URL url, Set<String> set) throws IOException {
  45. InputStream is = null;
  46. BufferedReader reader = null;
  47. try {
  48. is = url.openStream();
  49. reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
  50. for (;;) {
  51. String line = reader.readLine();
  52. if (line == null) {
  53. break;
  54. }
  55. int ci = line.indexOf('#');
  56. if (ci >= 0) {
  57. line = line.substring(0, ci);
  58. }
  59. line = line.trim();
  60. if (line.length() == 0) {
  61. continue;
  62. }
  63. set.add(line);
  64. }
  65. } finally {
  66. close(reader);
  67. close(is);
  68. }
  69. }
  70. public static void close(Closeable x) throws IOException {
  71. if (x != null) {
  72. x.close();
  73. }
  74. }
  75. }