當前位置: 首頁>>代碼示例>>Java>>正文


Java Key類代碼示例

本文整理匯總了Java中com.google.inject.Key的典型用法代碼示例。如果您正苦於以下問題:Java Key類的具體用法?Java Key怎麽用?Java Key使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Key類屬於com.google.inject包,在下文中一共展示了Key類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getBean

import com.google.inject.Key; //導入依賴的package包/類
@SuppressWarnings("unchecked")
@Override
public <T> T getBean(String beanId)
{
	Injector injector = ensureInjector();
	Key<Object> nameKey = Key.get(Object.class, Names.named(beanId));
	Binding<Object> binding = injector.getExistingBinding(nameKey);
	if( binding != null )
	{
		return (T) binding.getProvider().get();
	}
	ClassLoader classLoader = privatePluginService.getClassLoader(pluginId);
	try
	{
		Class<?> clazz = classLoader.loadClass(beanId);
		return (T) injector.getInstance(clazz);
	}
	catch( ClassNotFoundException e )
	{
		throw new RuntimeException(e);
	}
}
 
開發者ID:equella,項目名稱:Equella,代碼行數:23,代碼來源:GuicePlugin.java

示例2: extractConstructorParameters

import com.google.inject.Key; //導入依賴的package包/類
/**
 * Matches constructor parameters to method parameters for injection and records remaining parameters as required keys.
 */
private String[] extractConstructorParameters(Key<?> factoryKey, TypeLiteral<?> implementation, Constructor constructor, List<Key<?>> methodParams,
                                              Errors errors, Set<Dependency> dependencyCollector) throws ErrorsException {

    // Get parameters with annotations.
    List<TypeLiteral<?>> ctorParams = implementation.getParameterTypes(constructor);
    Annotation[][] ctorParamAnnotations = constructor.getParameterAnnotations();

    int p = 0;
    String[] parameterNames = new String[ctorParams.size()];
    for (TypeLiteral<?> ctorParam : ctorParams) {
        Key<?> ctorParamKey = getKey(ctorParam, constructor, ctorParamAnnotations[p], errors);

        if (ctorParamKey.getAnnotationType() == Assisted.class) {
            int location = methodParams.indexOf(ctorParamKey);

            // This should never happen since the constructor was already checked
            // in #[inject]constructorHasMatchingParams(..).
            Preconditions.checkState(location != -1);

            parameterNames[p] = ReflectUtil.formatParameterName(location);
        } else {
            dependencyCollector.add(new Dependency(factoryKey, ctorParamKey, false, true, constructor.toString()));
        }

        p++;
    }

    return parameterNames;
}
 
開發者ID:YoungDigitalPlanet,項目名稱:empiria.player,代碼行數:33,代碼來源:FactoryBinding.java

示例3: GuiceQueryPluginFactory

import com.google.inject.Key; //導入依賴的package包/類
@Inject
@SuppressWarnings("unchecked")
public GuiceQueryPluginFactory(Injector injector)
{
	m_injector = injector;
	Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();

	for (Key<?> key : bindings.keySet())
	{
		Class<?> bindingClass = key.getTypeLiteral().getRawType();
		if (QueryPlugin.class.isAssignableFrom(bindingClass))
		{
			PluginName ann = (PluginName) bindingClass.getAnnotation(PluginName.class);
			if (ann == null)
				throw new IllegalStateException("Aggregator class " + bindingClass.getName() +
						" does not have required annotation " + PluginName.class.getName());

			m_plugins.put(ann.name(), (Class<QueryPlugin>)bindingClass);
		}
	}
}
 
開發者ID:quqiangsheng,項目名稱:abhot,代碼行數:22,代碼來源:GuiceQueryPluginFactory.java

示例4: ConstructorBindingProvider

import com.google.inject.Key; //導入依賴的package包/類
ConstructorBindingProvider(Binder binder, Class<T> type, Key... keys) 
{
    super(binder, type, keys);
    
    Constructor<T> constructor = null;
    try 
    {
        constructor = type.getConstructor(getTypes());
    } 
    catch (NoSuchMethodException e) 
    {
        if (binder == null)
        {
            throw new IllegalArgumentException("no such constructor", e);
        }
        else
        {
            binder.addError(e);
        }
    }
    
    this.constructor = constructor;
}
 
開發者ID:parabuild-ci,項目名稱:parabuild-ci,代碼行數:24,代碼來源:BindUtil.java

示例5: ifCommmandIsInvalidExceptionIsThrown

import com.google.inject.Key; //導入依賴的package包/類
@Test
public void ifCommmandIsInvalidExceptionIsThrown() throws IOException, URISyntaxException {
    String command = "invalid";
    Map<String, Object> opts = new HashMap<>();
    opts.put(BROWSER, CHROME);
    opts.put(DRIVER, chromedriverFile.getAbsolutePath());
    opts.put(APPLICATION, configurationFile.getAbsolutePath());
    opts.put(URL, localhostUrl);
    opts.put(CASE, caseFile.getAbsolutePath());
    opts.put(SCREEN, screenString);
    opts.put(TIMEOUT, timeoutString);
    opts.put(PRECISION, precisionString);
    Module module = new DefaultModule(command, opts);
    Injector injector = Guice.createInjector(module);

    try {
        RequestFilter instance = injector.getInstance(
                Key.get(new TypeLiteral<IOProvider<RequestFilter>>() {})).get();
    } catch (ProvisionException e) {
        assertTrue(e.getCause() instanceof NoSuchCommandException);
    }
}
 
開發者ID:hristo-vrigazov,項目名稱:bromium,代碼行數:23,代碼來源:DefaultModuleTest.java

示例6: checkOnlyAcceptsPlayer

import com.google.inject.Key; //導入依賴的package包/類
private static boolean checkOnlyAcceptsPlayer(Class<? extends JCmd> executor) {
    for (InjectionPoint point : InjectionPoint.forInstanceMethodsAndFields(executor)) {
        if (!(point.getMember() instanceof Field))
            continue;

        Key<?> key = point.getDependencies().get(0).getKey();
        if (key.getTypeLiteral().getRawType().equals(Player.class)) {
            return true;
        }
    }

    return false;
}
 
開發者ID:Twister915,項目名稱:pl,代碼行數:14,代碼來源:JCommandExecutor.java

示例7: test

import com.google.inject.Key; //導入依賴的package包/類
@Test
public void test()
        throws Exception
{
    Annotation clientAnnotation = named("test");
    Bootstrap bootstrap = new Bootstrap(
            new DriftNettyClientModule(),
            binder -> configBinder(binder).bindConfig(DriftClientConfig.class, clientAnnotation, "prefix"));

    Injector injector = bootstrap
            .doNotInitializeLogging()
            .strictConfig()
            .initialize();

    assertNotNull(injector.getInstance(Key.get(new TypeLiteral<MethodInvokerFactory<Annotation>>() {})));
    assertNotNull(injector.getInstance(Key.get(DriftClientConfig.class, clientAnnotation)));
    assertNotNull(injector.getInstance(Key.get(DriftNettyClientConfig.class, clientAnnotation)));
}
 
開發者ID:airlift,項目名稱:drift,代碼行數:19,代碼來源:TestDriftNettyClientModule.java

示例8: addCreators

import com.google.inject.Key; //導入依賴的package包/類
private void addCreators()
{
    Injector injector = getInjector();
    for (Key<?> key : injector.getBindings().keySet())
    {
        Class<?> atype = key.getAnnotationType();
        if (atype != null && Remoted.class.isAssignableFrom(atype))
        {
            String scriptName = Remoted.class.cast(key.getAnnotation()).value();
            if (scriptName.equals(""))
            {
                Class cls = (Class) key.getTypeLiteral().getType();
                scriptName = cls.getSimpleName();
            }
            addCreator(scriptName, new InternalCreator(injector, key, scriptName));
        }
    }
}
 
開發者ID:parabuild-ci,項目名稱:parabuild-ci,代碼行數:19,代碼來源:InternalCreatorManager.java

示例9: canCreateReplayBrowserProvider

import com.google.inject.Key; //導入依賴的package包/類
@Test
public void canCreateReplayBrowserProvider() throws IOException, URISyntaxException {
    String command = REPLAY;
    Map<String, Object> opts = new HashMap<>();
    opts.put(BROWSER, CHROME);
    opts.put(DRIVER, chromedriverFile.getAbsolutePath());
    opts.put(APPLICATION, configurationFile.getAbsolutePath());
    opts.put(URL, localhostUrl);
    opts.put(CASE, caseFile.getAbsolutePath());
    opts.put(SCREEN, screenString);
    opts.put(TIMEOUT, timeoutString);
    opts.put(PRECISION, precisionString);

    Module module = new DefaultModule(command, opts);
    Injector injector = Guice.createInjector(module);
    IOURIProvider<ReplayBrowser> instance = injector.getInstance(new Key<IOURIProvider<ReplayBrowser>>() {});

    ReplayBrowser replayBrowser = instance.get();
    replayBrowser.forceCleanUp();
}
 
開發者ID:hristo-vrigazov,項目名稱:bromium,代碼行數:21,代碼來源:DefaultModuleTest.java

示例10: ModuleManifest

import com.google.inject.Key; //導入依賴的package包/類
public ModuleManifest(@Nullable TypeLiteral<Module> type) {
    // Figure out the module type. If the given type is null,
    // then try to resolve it from this object's superclass.
    this.type = type != null ? Types.assertFullySpecified(type)
                             : new ResolvableType<Module>(){}.in(getClass());
    this.rawType = (Class<Module>) this.type.getRawType();
    this.simpleName = rawType.getSimpleName();

    // Resolve the scope type automatically
    this.scope = (Class<Scope>) new ResolvableType<Scope>(){}.in(getClass()).getRawType();

    // Construct various keys related to the module/scope
    this.key = Key.get(this.type);
    this.optionalKey = Keys.optional(this.key);
    this.wrapperKey = ProvisionWrapper.keyOf(this.type);
    this.contextKey = Key.get(new ResolvableType<Context>(){}.in(getClass()));
    this.setElementKey = Key.get(new ResolvableType<ProvisionWrapper<? extends Base>>(){}.in(getClass()));
}
 
開發者ID:OvercastNetwork,項目名稱:ProjectAres,代碼行數:19,代碼來源:ModuleManifest.java

示例11: FactoryBinding

import com.google.inject.Key; //導入依賴的package包/類
FactoryBinding(Map<Key<?>, TypeLiteral<?>> collector, Key<?> factoryKey, Context context, GuiceUtil guiceUtil, MethodCallUtil methodCallUtil) {
    super(context, factoryKey);

    this.collector = Preconditions.checkNotNull(collector);
    this.factoryKey = factoryKey;
    this.factoryType = factoryKey.getTypeLiteral();
    this.guiceUtil = guiceUtil;
    this.methodCallUtil = methodCallUtil;

    try {
        matchMethods(Preconditions.checkNotNull(factoryKey));
    } catch (ErrorsException e) {
        e.getErrors().throwConfigurationExceptionIfErrorsExist();
    }
}
 
開發者ID:YoungDigitalPlanet,項目名稱:empiria.player,代碼行數:16,代碼來源:FactoryBinding.java

示例12: injectConstructorHasMatchingParams

import com.google.inject.Key; //導入依賴的package包/類
/**
 * Matching logic for {@literal @}{@link Inject} constructor and method parameters.
 * <p/>
 * This returns true if all assisted parameters required by the constructor are provided by the factory method.
 */
private boolean injectConstructorHasMatchingParams(TypeLiteral<?> type, Constructor<?> constructor, List<Key<?>> paramList, Errors errors)
        throws ErrorsException {
    List<TypeLiteral<?>> params = type.getParameterTypes(constructor);
    Annotation[][] paramAnnotations = constructor.getParameterAnnotations();
    int p = 0;
    for (TypeLiteral<?> param : params) {
        Key<?> paramKey = getKey(param, constructor, paramAnnotations[p++], errors);
        if (paramKey.getAnnotationType() == Assisted.class && !paramList.contains(paramKey)) {
            return false;
        }
    }

    return true;
}
 
開發者ID:YoungDigitalPlanet,項目名稱:empiria.player,代碼行數:20,代碼來源:FactoryBinding.java

示例13: forInnerClass

import com.google.inject.Key; //導入依賴的package包/類
public static <I> InnerFactoryManifest<?, I> forInnerClass(Key<I> key) {
    final Class<?> outer = key.getTypeLiteral().getRawType().getEnclosingClass();
    if(outer == null) {
        throw new IllegalArgumentException(key + " is not an inner class");
    }
    return new InnerFactoryManifest(key, TypeLiteral.get(outer));
}
 
開發者ID:OvercastNetwork,項目名稱:ProjectAres,代碼行數:8,代碼來源:InnerFactoryManifest.java

示例14: onProvision

import com.google.inject.Key; //導入依賴的package包/類
@Override
public <T> void onProvision(ProvisionInvocation<T> provision) {
  final Key<?> key = provision.getBinding().getKey();
  final Class<?> clazz = key.getTypeLiteral().getRawType();

  final T injectee = provision.provision();

  // Skip the shutdown manager since it's circular and doesn't have any lifecycle methods
  if (injectee instanceof LifecycleShutdownManager
      || injectee instanceof LifecycleProvisionListener) {
    return;
  }

  List<InvokableLifecycleMethod> postConstructMethods = findPostConstructMethods(injectee, clazz);
  List<InvokableLifecycleMethod> preDestroyMethods = findPreDestroyMethods(injectee, clazz);

  for (InvokableLifecycleMethod postConstructMethod : postConstructMethods) {
    try {
      postConstructMethod.invoke();
    } catch (Exception e) {
      throw new ProvisionException("Fail to provision object of type " + key, e);
    }
  }

  if (!preDestroyMethods.isEmpty()) {
    shutdownManager.addPreDestroyMethods(preDestroyMethods);
  }
}
 
開發者ID:cerner,項目名稱:beadledom,代碼行數:29,代碼來源:LifecycleProvisionListener.java

示例15: configure

import com.google.inject.Key; //導入依賴的package包/類
@Override
protected void configure() {
  OptionalBinder
      .newOptionalBinder(
          binder(),
          Key.get(String.class, CorrelationIdClientHeader.class))
      .setDefault().toInstance(CorrelationIdContext.DEFAULT_HEADER_NAME);

  OptionalBinder
      .newOptionalBinder(
          binder(),
          Key.get(BeadledomClientConfiguration.class, clientBindingAnnotation));

  install(new BeadledomClientPrivateModule(clientBindingAnnotation));
}
 
開發者ID:cerner,項目名稱:beadledom,代碼行數:16,代碼來源:BeadledomClientModule.java


注:本文中的com.google.inject.Key類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。