コード例 #1
0
  /**
   * Replaces or adds a service. The replacement is based on the service class.
   *
   * @param newService The new service to set.
   */
  public synchronized void set(Service newService) {
    List<Service> services = new CopyOnWriteArrayList<Service>();
    Service service;
    boolean replaced = false;

    for (int i = 0; (i < size()); i++) {
      service = get(i);

      if (service != null) {
        if (service.getClass().isAssignableFrom(newService.getClass())) {
          try {
            service.stop();
          } catch (Exception e) {
            Context.getCurrentLogger().log(Level.WARNING, "Unable to stop service replaced", e);
          }

          services.add(newService);
          replaced = true;
        } else {
          services.add(service);
        }
      }
    }

    if (!replaced) {
      services.add(newService);
    }

    set(services);
  }
コード例 #2
0
  /**
   * Returns a service matching a given service class.
   *
   * @param <T> The service type.
   * @param clazz The service class to match.
   * @return The matched service instance.
   */
  @SuppressWarnings("unchecked")
  public <T extends Service> T get(Class<T> clazz) {
    for (Service service : this) {
      if (clazz.isAssignableFrom(service.getClass())) {
        return (T) service;
      }
    }

    return null;
  }