Java 类com.google.inject.internal.Annotations 实例源码

项目:bootique-jersey-client    文件:ClientGuiceInjectInjector.java   
@Override
public Object resolve(Injectee injectee, ServiceHandle<?> serviceHandle) {

    if (injectee.getRequiredType() instanceof Class) {

        TypeLiteral<?> typeLiteral = TypeLiteral.get(injectee.getRequiredType());
        Errors errors = new Errors(injectee.getParent());
        Key<?> key;
        try {
            key = Annotations.getKey(typeLiteral, (Member) injectee.getParent(),
                    injectee.getParent().getDeclaredAnnotations(), errors);
        } catch (ErrorsException e) {
            errors.merge(e.getErrors());
            throw new ConfigurationException(errors.getMessages());
        }

        return injector.getInstance(key);
    }

    throw new IllegalStateException("Can't process injection point: " + injectee.getRequiredType());
}
项目:bootique-jersey    文件:GuiceInjectInjector.java   
@Override
public Object resolve(Injectee injectee, ServiceHandle<?> serviceHandle) {

    if (injectee.getRequiredType() instanceof Class) {

        TypeLiteral<?> typeLiteral = TypeLiteral.get(injectee.getRequiredType());
        Errors errors = new Errors(injectee.getParent());
        Key<?> key;
        try {
            key = Annotations.getKey(typeLiteral, (Member) injectee.getParent(),
                    injectee.getParent().getDeclaredAnnotations(), errors);
        } catch (ErrorsException e) {
            errors.merge(e.getErrors());
            throw new ConfigurationException(errors.getMessages());
        }

        return injector.getInstance(key);
    }

    throw new IllegalStateException("Can't process injection point: " + injectee.getRequiredType());
}
项目:guice    文件:FactoryProvider2Test.java   
public void testDuplicateKeys() {
  try {
    Guice.createInjector(
        new AbstractModule() {
          @Override
          protected void configure() {
            bind(DoubleToneCarFactory.class)
                .toProvider(FactoryProvider.newFactory(DoubleToneCarFactory.class, Maxima.class));
          }
        });
    fail();
  } catch (CreationException expected) {
    assertContains(
        expected.getMessage(),
        "A binding to "
            + Color.class.getName()
            + " annotated with @"
            + Assisted.class.getName()
            + "(value="
            + Annotations.memberValueString("paint")
            + ") was already configured at");
  }
}
项目:guice    文件:InjectionPoint.java   
/** Returns true if the binding annotation is in the wrong place. */
private static boolean checkForMisplacedBindingAnnotations(Member member, Errors errors) {
  Annotation misplacedBindingAnnotation =
      Annotations.findBindingAnnotation(
          errors, member, ((AnnotatedElement) member).getAnnotations());
  if (misplacedBindingAnnotation == null) {
    return false;
  }

  // don't warn about misplaced binding annotations on methods when there's a field with the same
  // name. In Scala, fields always get accessor methods (that we need to ignore). See bug 242.
  if (member instanceof Method) {
    try {
      if (member.getDeclaringClass().getDeclaredField(member.getName()) != null) {
        return false;
      }
    } catch (NoSuchFieldException ignore) {
    }
  }

  errors.misplacedBindingAnnotation(member, misplacedBindingAnnotation);
  return true;
}
项目:guice    文件:ImplicitBindingTest.java   
public void testNoImplicitBindingIsCreatedForAnnotatedKeys() {
  try {
    Guice.createInjector().getInstance(Key.get(I.class, Names.named("i")));
    fail();
  } catch (ConfigurationException expected) {
    Asserts.assertContains(
        expected.getMessage(),
        "1) No implementation for " + I.class.getName(),
        "annotated with @"
            + Named.class.getName()
            + "(value="
            + Annotations.memberValueString("i")
            + ") was bound.",
        "while locating " + I.class.getName(),
        " annotated with @"
            + Named.class.getName()
            + "(value="
            + Annotations.memberValueString("i")
            + ")");
  }
}
项目:guice    文件:NamedEquivalanceTest.java   
private static void assertDuplicateBinding(Module a, Module b, boolean fails) {
  try {
    Guice.createInjector(a, b);
    if (fails) {
      fail("should have thrown CreationException");
    }
  } catch (CreationException e) {
    if (fails) {
      assertContains(
          e.getMessage(),
          "A binding to java.lang.String annotated with @com.google.inject.name.Named(value="
              + Annotations.memberValueString("foo")
              + ") was already configured");
    } else {
      throw e;
    }
  }
}
项目:guice-old    文件:InjectionPoint.java   
/**
 * Returns true if the binding annotation is in the wrong place.
 */
private static boolean checkForMisplacedBindingAnnotations(Member member, Errors errors) {
  Annotation misplacedBindingAnnotation = Annotations.findBindingAnnotation(
      errors, member, ((AnnotatedElement) member).getAnnotations());
  if (misplacedBindingAnnotation == null) {
    return false;
  }

  // don't warn about misplaced binding annotations on methods when there's a field with the same
  // name. In Scala, fields always get accessor methods (that we need to ignore). See bug 242.
  if (member instanceof Method) {
    try {
      if (member.getDeclaringClass().getDeclaredField(member.getName()) != null) {
        return false;
      }
    } catch (NoSuchFieldException ignore) {
    }
  }

  errors.misplacedBindingAnnotation(member, misplacedBindingAnnotation);
  return true;
}
项目:guice-ext-annotations    文件:DynamicClassGenerator.java   
@SuppressWarnings("PMD.UnusedPrivateMethod")
private static void applyScopeAnnotation(final ClassPool classPool, final AnnotationsAttribute annotations,
                                         final AnnotatedElement source,
                                         final Class<? extends java.lang.annotation.Annotation> scope)
        throws Exception {
    if (scope != null) {
        Preconditions.checkState(Annotations.isScopeAnnotation(scope),
                "Provided annotation %s is not scope annotation", scope.getSimpleName());
        for (java.lang.annotation.Annotation ann : source.getAnnotations()) {
            Preconditions.checkArgument(!(ann instanceof ScopeAnnotation),
                    "Duplicate scope definition: scope is specified as %s and also defined "
                            + "in @ScopeAnnotation.", scope.getSimpleName());
        }
        annotations.addAnnotation(new Annotation(annotations.getConstPool(), classPool.get(scope.getName())));
    }
}
项目:stdlib    文件:AutomockAnnotatedMockModule.java   
@Override
protected void configure()
{
    final Errors errors = new Errors(testClass);

    for (FrameworkField field : fields)
    {
        try
        {
            final Field f = field.getField();
            final Key key = Annotations.getKey(TypeLiteral.get(f.getGenericType()), f, field.getAnnotations(), errors);

            bindMock(key, f.getType(), "Automock[" + field.getName() + "] " + key);
        }
        catch (ErrorsException e)
        {
            // Add it to the error list and hold them all until the end
            errors.merge(e.getErrors());
        }
    }

    errors.throwConfigurationExceptionIfErrorsExist();
}
项目:google-guice    文件:InjectionPoint.java   
/**
 * Returns true if the binding annotation is in the wrong place.
 */
private static boolean checkForMisplacedBindingAnnotations(Member member, Errors errors) {
  Annotation misplacedBindingAnnotation = Annotations.findBindingAnnotation(
      errors, member, ((AnnotatedElement) member).getAnnotations());
  if (misplacedBindingAnnotation == null) {
    return false;
  }

  // don't warn about misplaced binding annotations on methods when there's a field with the same
  // name. In Scala, fields always get accessor methods (that we need to ignore). See bug 242.
  if (member instanceof Method) {
    try {
      if (member.getDeclaringClass().getDeclaredField(member.getName()) != null) {
        return false;
      }
    } catch (NoSuchFieldException ignore) {
    }
  }

  errors.misplacedBindingAnnotation(member, misplacedBindingAnnotation);
  return true;
}
项目:ProjectAres    文件:InjectableMethod.java   
private <D> InjectableMethod(@Nullable TypeLiteral<D> targetType, @Nullable D target, Method method, @Nullable T result) {
    final Errors errors = new Errors(method);

    if(Members.isStatic(method)) {
        checkArgument(target == null);
    } else {
        checkArgument(target != null);
    }

    targetType = targetType(targetType, target, method);

    checkArgument(method.getDeclaringClass().isAssignableFrom(targetType.getRawType()));

    this.method = method;
    this.dependencies = ImmutableSet.copyOf(InjectionPoint.forMethod(method, targetType).getDependencies());

    if(result != null) {
        this.result = result;
        this.providedKey = Keys.forInstance(result);
    } else {
        final TypeLiteral<T> returnType = (TypeLiteral<T>) targetType.getReturnType(method);
        if(!Void.class.equals(returnType.getRawType())) {
            final Annotation qualifier = Annotations.findBindingAnnotation(errors, method, method.getAnnotations());
            this.result = null;
            this.providedKey = Keys.get(returnType, qualifier);
        } else {
            this.result = (T) this;
            this.providedKey = Keys.forInstance(this.result);
        }
    }

    this.scope = Annotations.findScopeAnnotation(errors, method.getAnnotations());

    MethodHandle handle = MethodHandleUtils.privateUnreflect(method);
    if(target != null) {
        handle = handle.bindTo(target);
    }
    this.handle = handle;
}
项目:Equella    文件:GuicePlugin.java   
@Override
protected void doStart() throws Exception
{
    // Please do not remove
    // This kludge is about ensuring these annotations are parsed to prevent
    // a deadlock
    Annotations.isRetainedAtRuntime(Assisted.class);
    Annotations.isRetainedAtRuntime(AssistedInject.class);
    Annotations.isRetainedAtRuntime(BindingAnnotation.class);
    // End kludge
    privatePluginService = (PrivatePluginService) AbstractPluginService.get();
    getManager().getRegistry().registerListener(this);
    setupBeanLocators();
}
项目:marshalsec    文件:MockProxies.java   
private static Object makeProxyGuice ( String method, Object iter, Class<?>... types ) throws Exception {
    Method meth = Annotations.class.getDeclaredMethod("generateAnnotationImpl", Class.class); //$NON-NLS-1$
    meth.setAccessible(true);
    Object o = meth.invoke(null, Override.class);
    InvocationHandler inv = Proxy.getInvocationHandler(o);
    Map<String, Object> values = new HashMap<>();
    values.put(method, iter);
    Reflections.setFieldValue(inv, "val$members", values);
    return Proxy.newProxyInstance(MockProxies.class.getClassLoader(), types, inv);
}
项目:salta    文件:Key.java   
/**
 * Gets the strategy for an annotation.
 */
static AnnotationStrategy strategyFor(Annotation annotation) {
    checkNotNull(annotation, "annotation");
    Class<? extends Annotation> annotationType = annotation
            .annotationType();
    ensureRetainedAtRuntime(annotationType);
    ensureIsBindingAnnotation(annotationType);

    if (Annotations.isMarker(annotationType)) {
        return new AnnotationTypeStrategy(annotationType, annotation);
    }

    return new AnnotationInstanceStrategy(
            Annotations.canonicalizeIfNamed(annotation));
}
项目:salta    文件:Key.java   
/**
 * Gets the strategy for an annotation type.
 */
static AnnotationStrategy strategyFor(
        Class<? extends Annotation> annotationType) {
    annotationType = Annotations.canonicalizeIfNamed(annotationType);
    if (isAllDefaultMethods(annotationType)) {
        return strategyFor(generateAnnotation(annotationType));
    }

    checkNotNull(annotationType, "annotation type");
    ensureRetainedAtRuntime(annotationType);
    ensureIsBindingAnnotation(annotationType);
    return new AnnotationTypeStrategy(annotationType, null);

}
项目:miscellaneous    文件:Providers.java   
Providers(@Nullable T providersInstance, Class<T> providerClass) {
  this.providersInstance = providersInstance;
  this.providersClass = providerClass;
  this.source = StackTraceElements.forType(providersClass);
  this.type = TypeToken.of(providersClass);
  this.errors = new Errors(source);
  this.scopeAnnotation = Annotations.findScopeAnnotation(errors, providersClass);
  this.providers = introspectProviders();
}
项目:miscellaneous    文件:Providers.java   
private EventualProvider<?> providerFor(Invokable<T, ?> method, Errors methodErrors) {
  Annotation[] annotations = method.getAnnotations();

  verifyMethodAccessibility(methodErrors, method, source);

  @Nullable Annotation bindingAnnotation =
      Annotations.findBindingAnnotation(methodErrors, method, annotations);

  verifyAbsenseOfScopeAnnotation(methodErrors, annotations, source);

  List<Dependency<ListenableFuture<?>>> dependencies =
      Lists.newArrayListWithCapacity(method.getParameters().size());

  for (Parameter parameter : method.getParameters()) {
    dependencies.add(extractDependency(methodErrors, parameter));
  }

  Key<ListenableFuture<?>> bindingKey;
  boolean exposedBinding = method.isAnnotationPresent(Exposed.class);

  if (isVoid(method)) {
    bindingKey = futureKey(TypeToken.of(Boolean.class), new BlackholedAnnotation());
    exposedBinding = false;
  } else {
    bindingKey = futureKey(method.getReturnType(), bindingAnnotation);
  }

  return new EventualProvider<>(
      method,
      exposedBinding,
      dependencies,
      bindingKey,
      scopeAnnotation,
      source);
}
项目:miscellaneous    文件:Providers.java   
private void verifyAbsenseOfScopeAnnotation(Errors methodErrors, Annotation[] annotations, Object source) {
  @Nullable Class<? extends Annotation> methodScopeAnnotation =
      Annotations.findScopeAnnotation(methodErrors, annotations);
  if (methodScopeAnnotation != null) {
    methodErrors.addMessage(
        "Misplaced scope annotation @%s on method @%s %s."
            + "\n\tScope annotation will only be inherited from enclosing class %s",
        methodScopeAnnotation.getSimpleName(),
        Eventually.Provides.class.getSimpleName(),
        source,
        providersClass.getSimpleName());
  }
}
项目:miscellaneous    文件:Providers.java   
Dependency<ListenableFuture<?>> extractDependency(Errors methodErrors, Parameter parameter) {
  @Nullable Annotation bindingAnnotation =
      Annotations.findBindingAnnotation(
          methodErrors,
          parameter.getDeclaringInvokable(),
          parameter.getAnnotations());

  return Dependency.get(futureKey(
      parameter.getType(),
      bindingAnnotation));
}
项目:guice    文件:BoundFieldModule.java   
private LinkedBindingBuilder<?> verifyBindingAnnotations(
    Field field, AnnotatedBindingBuilder<?> annotatedBinder) {
  LinkedBindingBuilder<?> binderRet = annotatedBinder;
  for (Annotation annotation : field.getAnnotations()) {
    Class<? extends Annotation> annotationType = annotation.annotationType();
    if (Annotations.isBindingAnnotation(annotationType)) {
      // not returning here ensures that annotatedWith will be called multiple times if this field
      // has multiple BindingAnnotations, relying on the binder to throw an error in this case.
      binderRet = annotatedBinder.annotatedWith(annotation);
    }
  }
  return binderRet;
}
项目:guice    文件:Struts2Factory.java   
/** Returns true if the given class has a scope annotation. */
private static boolean hasScope(Class<? extends Interceptor> interceptorClass) {
  for (Annotation annotation : interceptorClass.getAnnotations()) {
    if (Annotations.isScopeAnnotation(annotation.annotationType())) {
      return true;
    }
  }
  return false;
}
项目:guice    文件:GuiceObjectFactory.java   
/** Returns true if the given class has a scope annotation. */
private static boolean hasScope(Class<? extends Interceptor> interceptorClass) {
  for (Annotation annotation : interceptorClass.getAnnotations()) {
    if (Annotations.isScopeAnnotation(annotation.annotationType())) {
      return true;
    }
  }
  return false;
}
项目:guice    文件:Parameter.java   
/**
 * Returns the unique binding annotation from the specified list, or {@code null} if there are
 * none.
 *
 * @throws IllegalStateException if multiple binding annotations exist.
 */
private Annotation getBindingAnnotation(Annotation[] annotations) {
  Annotation bindingAnnotation = null;
  for (Annotation annotation : annotations) {
    if (Annotations.isBindingAnnotation(annotation.annotationType())) {
      checkArgument(
          bindingAnnotation == null,
          "Parameter has multiple binding annotations: %s and %s",
          bindingAnnotation,
          annotation);
      bindingAnnotation = annotation;
    }
  }
  return bindingAnnotation;
}
项目:guice    文件:FactoryProvider2.java   
@Override
public String toString() {
  return "@"
      + Assisted.class.getName()
      + "(value="
      + Annotations.memberValueString("")
      + ")";
}
项目:guice    文件:CheckedProvideUtils.java   
@SuppressWarnings("unchecked") // safe because it's a constructor of the typeLiteral
static <T> Constructor<? extends T> findThrowingConstructor(
    TypeLiteral<? extends T> typeLiteral, Binder binder) {

  Class<?> rawType = typeLiteral.getRawType();
  Errors errors = new Errors(rawType);
  Constructor<?> cxtor = null;
  for (Constructor<?> constructor : rawType.getDeclaredConstructors()) {
    if (constructor.isAnnotationPresent(ThrowingInject.class)) {
      if (cxtor != null) {
        errors.addMessage(
            "%s has more than one constructor annotated with @ThrowingInject. "
                + CONSTRUCTOR_RULES,
            rawType);
      }

      cxtor = constructor;
      Annotation misplacedBindingAnnotation =
          Annotations.findBindingAnnotation(
              errors, cxtor, ((AnnotatedElement) cxtor).getAnnotations());
      if (misplacedBindingAnnotation != null) {
        errors.misplacedBindingAnnotation(cxtor, misplacedBindingAnnotation);
      }
    }
  }

  if (cxtor == null) {
    errors.addMessage(
        "Could not find a suitable constructor in %s. " + CONSTRUCTOR_RULES, rawType);
  }

  for (Message msg : errors.getMessages()) {
    binder.addError(msg);
  }
  return (Constructor<? extends T>) cxtor;
}
项目:guice    文件:Key.java   
/** Gets the strategy for an annotation. */
static AnnotationStrategy strategyFor(Annotation annotation) {
  checkNotNull(annotation, "annotation");
  Class<? extends Annotation> annotationType = annotation.annotationType();
  ensureRetainedAtRuntime(annotationType);
  ensureIsBindingAnnotation(annotationType);

  if (Annotations.isMarker(annotationType)) {
    return new AnnotationTypeStrategy(annotationType, annotation);
  }

  return new AnnotationInstanceStrategy(Annotations.canonicalizeIfNamed(annotation));
}
项目:guice    文件:Key.java   
/** Gets the strategy for an annotation type. */
static AnnotationStrategy strategyFor(Class<? extends Annotation> annotationType) {
  annotationType = Annotations.canonicalizeIfNamed(annotationType);
  if (isAllDefaultMethods(annotationType)) {
    return strategyFor(generateAnnotation(annotationType));
  }

  checkNotNull(annotationType, "annotation type");
  ensureRetainedAtRuntime(annotationType);
  ensureIsBindingAnnotation(annotationType);
  return new AnnotationTypeStrategy(annotationType, null);
}
项目:guice    文件:PrivateModuleTest.java   
/**
 * Ensure that when we've got errors in different private modules, Guice presents all errors in a
 * unified message.
 */
public void testMessagesFromPrivateModulesAreNicelyIntegrated() {
  try {
    Guice.createInjector(
        new PrivateModule() {
          @Override
          public void configure() {
            bind(C.class);
          }
        },
        new PrivateModule() {
          @Override
          public void configure() {
            bind(AB.class);
          }
        });
    fail();
  } catch (CreationException expected) {
    assertContains(
        expected.getMessage(),
        "1) No implementation for " + C.class.getName() + " was bound.",
        "at " + getClass().getName(),
        getDeclaringSourcePart(getClass()),
        "2) No implementation for " + String.class.getName(),
        "Named(value=" + Annotations.memberValueString("a") + ") was bound.",
        "for field at " + AB.class.getName() + ".a(PrivateModuleTest.java:",
        "3) No implementation for " + String.class.getName(),
        "Named(value=" + Annotations.memberValueString("b") + ") was bound.",
        "for field at " + AB.class.getName() + ".b(PrivateModuleTest.java:",
        "3 errors");
  }
}
项目:guice    文件:BindingTest.java   
public void testMissingAnnotationOneChoice() {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @SuppressWarnings("unchecked")
    @Override
    public void configure() {
      bind(Bacon.class).annotatedWith(named("Turkey")).to(TurkeyBacon.class);
    }
  });

  try {
    // turkey typo (should be Upper case)...
    injector.getInstance(Key.get(Bacon.class, named("turkey")));
    fail();
  } catch (ConfigurationException e) {
    String msg = e.getMessage();
    assertContains(msg, "Guice configuration errors:");
    assertContains(
        msg,
        "1) No implementation for com.google.inject.BindingTest$Bacon"
            + " annotated with"
            + " @com.google.inject.name.Named(value="
            + Annotations.memberValueString("turkey")
            + ") was bound.",
        "Did you mean?",
        "* com.google.inject.BindingTest$Bacon annotated with"
            + " @com.google.inject.name.Named(value="
            + Annotations.memberValueString("Turkey")
            + ")",
        "while locating com.google.inject.BindingTest$Bacon annotated with"
            + " @com.google.inject.name.Named(value="
            + Annotations.memberValueString("turkey")
            + ")");
  }
}
项目:guice    文件:NamedEquivalanceTest.java   
private static void assertMissingBindingErrorMessageUsesType(Class<?> clientType) {
  try {
    Guice.createInjector().getInstance(clientType);
    fail("should have thrown ConfigurationException");
  } catch (ConfigurationException e) {
    assertContains(
        e.getMessage(),
        "No implementation for java.lang.String annotated with "
            + "@com.google.inject.name.Named(value="
            + Annotations.memberValueString("foo")
            + ") was bound.");
  }
}
项目:guice    文件:NamedEquivalanceTest.java   
@Override
public String toString() {
  return "@"
      + javax.inject.Named.class.getName()
      + "(value="
      + Annotations.memberValueString(value)
      + ")";
}
项目:guice    文件:NamedEquivalanceTest.java   
@Override
public String toString() {
  return "@"
      + com.google.inject.name.Named.class.getName()
      + "(value="
      + Annotations.memberValueString(value)
      + ")";
}
项目:guice    文件:MembersInjectorTest.java   
public void testGettingAnnotatedMembersInjector() {
  Injector injector = Guice.createInjector();
  try {
    injector.getInstance(new Key<MembersInjector<String>>(Names.named("foo")) {});
    fail();
  } catch (ConfigurationException expected) {
    assertContains(
        expected.getMessage(),
        "1) No implementation for com.google.inject.MembersInjector<java.lang.String> "
            + "annotated with @com.google.inject.name.Named(value="
            + Annotations.memberValueString("foo")
            + ") was bound.");
  }
}
项目:guice-old    文件:BoundFieldModule.java   
private LinkedBindingBuilder<?> verifyBindingAnnotations(
    Field field,
    AnnotatedBindingBuilder<?> annotatedBinder) {
  LinkedBindingBuilder<?> binderRet = annotatedBinder;
  for (Annotation annotation : field.getAnnotations()) {
    Class<? extends Annotation> annotationType = annotation.annotationType();
    if (Annotations.isBindingAnnotation(annotationType)) {
      // not returning here ensures that annotatedWith will be called multiple times if this field
      // has multiple BindingAnnotations, relying on the binder to throw an error in this case.
      binderRet = annotatedBinder.annotatedWith(annotation);
    }
  }
  return binderRet;
}
项目:guice-old    文件:Struts2Factory.java   
/**
 * Returns true if the given class has a scope annotation.
 */
private static boolean hasScope(Class<? extends Interceptor> interceptorClass) {
  for (Annotation annotation : interceptorClass.getAnnotations()) {
    if (Annotations.isScopeAnnotation(annotation.annotationType())) {
      return true;
    }
  }
  return false;
}
项目:guice-old    文件:GuiceObjectFactory.java   
/**
 * Returns true if the given class has a scope annotation.
 */
private static boolean hasScope(Class<? extends Interceptor> interceptorClass) {
  for (Annotation annotation : interceptorClass.getAnnotations()) {
    if (Annotations.isScopeAnnotation(annotation.annotationType())) {
      return true;
    }
  }
  return false;
}