11

先日、使用中に不都合がjava.util.ServiceLoaderあり、いくつかの質問がありました。

一般的なサービスがあるとします。

public interface Service<T> { ... }

特定のジェネリック型を持つ実装のみServiceLoaderをロードするように明示的に指示することはできませんでした。

ServiceLoader<Service<String>> services = 
   ServiceLoader.load(Service.class); // Fail.

私の質問はServiceLoader、一般的なサービスの実装を安全にロードするために使用する合理的な方法は何ですか?


上記の質問をした後、Paŭlo の回答の前に、解決策を思いつくことができました。

public interface Service<T> { ...
    // true if an implementation can handle the given `t' type; false otherwise.
    public boolean canHandle(Class<?> t) { ...

public final class StringService implements Service<String> { ...
    @Override public boolean canHandle(Class<?> t) {
        if (String.class.isAssignableFrom(type)) 
            return true;
        return false;
    }

public final class DoubleService implements Service<Double> { ...
    // ...

public final class Services { ...
    public static <T> Service<T> getService(Class<?> t) {
        for (Service<T> s : ServiceLoader.load(Service.class))
            if (s.canServe(t))
                return s;
        throw new UnsupportedOperationException("No servings today my son!");
    }

同じ方法での変更boolean canServe(Class<?> t)boolean canServe(Object o)変更は、より動的になる可能性があります(最初にインターフェイスに<T> Service<T> getService(Class<?> t)メソッドがあったため、後者を自分で使用しています)。boolean canHandle(T t)

4

2 に答える 2

7

ここでの問題は、サービスローダーが特定のクラス/インターフェイスのすべての実装をリストするファイルを使用していることです。このファイルはインターフェイス名で名前が付けられています。Classtypeパラメーターをこのファイル名に入れることは予測されていませんでした。また、ジェネリック型をオブジェクトとして渡すことも実際には不可能です。

したがって、ここでは、任意のタイプの汎用サービスのみを取得し、それらのクラスオブジェクトを調べて、それがのサブタイプであるかどうかを確認できますService<String>

このようなもの:

class Test{

    public Service<String> getStringService() {
        // it is a bit strange that we can't explicitely construct a
        // parametrized type from raw type and parameters, so here
        // we use this workaround. This may need a dummy method or
        // variable if this method should have another return type.
        ParametrizedType stringServiceType =
            (ParametrizedType)Test.class.getMethod("getStringService").getGenericReturnType();

        ServiceLoader<Service<?>> loader = ServiceLoader.load(Service<?>.class);
        for(Service<?> service : loader) {
           if(isImplementing(service.getClass(), stringServiceType)) {
              @SuppressWarnings("unchecked")
              Service<String> s = (Service)service;
              return s;
           }
        }
    }

    public boolean isImplementing(Class<?> candidate, ParametrizedType t) {
        for(Type iFace : candidate.getGenericInterfaces()) {
           if(iFace.equals(t)) {
              return true;
           }
           if(iFace instanceof ParametrizedType &&
              ((ParametrizedType)iFace).getRawType().equals(t.getRawType())) {
              return false;
           }
        }
        return false;
    }

}

これはテストされておらず、クラスが直接実装するインターフェイスによって拡張されたインターフェイスや、(汎用)スーパークラスによって実装されたインターフェイスも検索するように拡張する必要がある場合があります。

そしてもちろん、これは次のようなクラスしか見つけることができません

class Example implements Service<String> { ...}

のようなものではありません

class Example<X> implements Service<X> { ... }

サービスの有効な実装はどこにあるExample<String>のでしょうか。

于 2011-03-27T21:44:15.083 に答える
0

また、ServiceLoaderクラスファイルをコピーして、load()メソッドからジェネリック型引数を削除し、常に機能させることもできます。警告を上書きする必要があります。

  public static <S> ServiceLoader load(final Class<S> service)
   {
      return load(service, Thread.currentThread().getContextClassLoader());
   }
于 2011-06-28T05:16:07.773 に答える