Java Code Examples for java.lang.reflect.Constructor#isAnnotationPresent()

The following examples show how to use java.lang.reflect.Constructor#isAnnotationPresent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractThriftMetadataBuilder.java    From drift with Apache License 2.0 6 votes vote down vote up
protected final void extractFromConstructors()
{
    if (builderType == null) {
        // struct class must have a valid constructor
        addConstructors(structType);
    }
    else {
        // builder class must have a valid constructor
        addConstructors(builderType);

        // builder class must have a build method annotated with @ThriftConstructor
        addBuilderMethods();

        // verify struct class does not have @ThriftConstructors
        for (Constructor<?> constructor : getStructClass().getConstructors()) {
            if (constructor.isAnnotationPresent(ThriftConstructor.class)) {
                metadataErrors.addWarning(
                        "Thrift class '%s' has a builder class, but constructor '%s' annotated with @ThriftConstructor",
                        getStructClass().getName(),
                        constructor);
            }
        }
    }
}
 
Example 2
Source File: ProviderConstructor.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
private Constructor<?> findConstructor()
{
  Constructor<?> ctorZero = null;
  
  for (Constructor<?> ctor : _type.getDeclaredConstructors()) {
    if (ctor.isAnnotationPresent(Inject.class)) {
      return ctor;
    }
    
    if (ctor.getParameterTypes().length == 0) {
      ctorZero = ctor;
    }
  }

  return ctorZero;
}
 
Example 3
Source File: AConstructorProcess.java    From JavaTutorial with MIT License 6 votes vote down vote up
public static void init(Object object) throws IllegalAccessException, InvocationTargetException, InstantiationException {
    if (object instanceof User) {
        Class clz = object.getClass();
        Constructor [] constructors = clz.getConstructors();
        for (Constructor constructor : constructors) {
            if (constructor.isAnnotationPresent(AConstructor.class)) {
                AConstructor aConstructor = (AConstructor) constructor.getAnnotation(AConstructor.class);
                String name = aConstructor.initName();
                int age = aConstructor.initAge();
                ((User) object).name = name;
                ((User) object).age = age;
            }
        }
    }else{
        throw new RuntimeException("无法向下转型到指定类");
    }

}
 
Example 4
Source File: ClassUtils.java    From oxygen with Apache License 2.0 5 votes vote down vote up
/**
 * 获取被注解的构造方法
 *
 * @param constructors 构造方法
 * @param annotation 注解
 * @return Constructor
 */
@SuppressWarnings("squid:S1452")
public Constructor<?> getConstructorAnnotatedWith(Constructor<?>[] constructors,
    Class<? extends Annotation> annotation) {
  for (Constructor<?> constructor : constructors) {
    if (constructor.isAnnotationPresent(annotation)) {
      return constructor;
    }
  }
  return null;
}
 
Example 5
Source File: ReflectionUtils.java    From base-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 获取constructor的annotationClass注解
 * 
 * @param constructor
 *            constructor对象
 * @param annotationClass
 *            annotationClass注解
 * 
 * @return {@link Annotation}
 */
public static <T extends Annotation> T getAnnotation(
		Constructor constructor, Class annotationClass) {

	Assert.notNull(constructor, "constructor不能为空");
	Assert.notNull(annotationClass, "annotationClass不能为空");

	constructor.setAccessible(true);

	if (constructor.isAnnotationPresent(annotationClass)) {
		return (T) constructor.getAnnotation(annotationClass);
	}

	return null;
}
 
Example 6
Source File: ComponentDescriptor.java    From fenixedu-cms with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Constructor<?> getCustomCtor(Class<?> type) {
    for (Constructor<?> ctor : type.getDeclaredConstructors()) {
        if (ctor.isAnnotationPresent(DynamicComponent.class) && !isJsonConstructor(ctor)) {
            return ctor;
        }
    }
    return ClassUtils.getConstructorIfAvailable(type);
}
 
Example 7
Source File: ConstructorAndPublicMethodsCliObjectFactory.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private boolean canUseConstructor(Constructor<?> constructor) {
  if (!Modifier.isPublic(constructor.getModifiers())) {
    return false;
  }
  if (!constructor.isAnnotationPresent(CliObjectSupport.class)) {
    return false;
  }
  for (Class<?> param : constructor.getParameterTypes()) {
    if (param != String.class) {
      return false;
    }
  }
  return constructor.getParameterTypes().length ==
      constructor.getAnnotation(CliObjectSupport.class).argumentNames().length;
}
 
Example 8
Source File: DatasourceValidator.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
public static List<String> validate(Class<? extends DataSource<?>> dsClass) {
    final ArrayList<String> errors = new ArrayList<>();
    int injectableConstructorCount = 0;
    final Constructor<?>[] declaredConstructors = dsClass.getDeclaredConstructors();
    for (Constructor<?> constructor : declaredConstructors) {
        if (constructor.getParameterCount() == 2) {
            continue;
        }

        if (!constructor.isAnnotationPresent(Inject.class)) {
            errors.add("Injectable constructor" + constructor.toGenericString() + "not annotated with @Inject");
            continue;
        }

        injectableConstructorCount++;
        final Parameter[] parameters = constructor.getParameters();
        final Set<String> datasourceRequestAttributes = new HashSet<>();
        for (Parameter parameter : parameters) {
            final RequestAttribute requestAttribute = parameter.getAnnotation(RequestAttribute.class);
            if (requestAttribute != null) {
                final String attribute = Optional.of(requestAttribute.value()).filter(StringUtils::isNotEmpty).orElse(parameter.getName());
                final boolean added = datasourceRequestAttributes.add(attribute);
                if (!added) {
                    errors.add("RequestAttribute: " + braced(attribute) + " is used twice");
                }
            }
        }
    }

    if (injectableConstructorCount > 1) {
        errors.add("More than 1 injectable constructor defined");
    }

    return errors;
}
 
Example 9
Source File: AnnotationsConfigurer.java    From oval with Eclipse Public License 2.0 5 votes vote down vote up
protected void configureCtorParamChecks(final ClassConfiguration classCfg) {
   for (final Constructor<?> ctor : classCfg.type.getDeclaredConstructors()) {

      /*
       * determine parameter checks
       */
      final List<ParameterConfiguration> paramCfgs = _createParameterConfigs( //
         ctor.getParameterTypes(), //
         ctor.getParameterAnnotations(), //
         ctor.getAnnotatedParameterTypes() //
      );

      /*
       * check if anything has been configured for this constructor at all
       */
      final boolean postValidateThis = ctor.isAnnotationPresent(PostValidateThis.class);
      if (postValidateThis || paramCfgs.size() > 0) {
         if (classCfg.constructorConfigurations == null) {
            classCfg.constructorConfigurations = getCollectionFactory().createSet(2);
         }

         final ConstructorConfiguration cc = new ConstructorConfiguration();
         cc.parameterConfigurations = paramCfgs;
         cc.postCheckInvariants = postValidateThis;
         classCfg.constructorConfigurations.add(cc);
      }
   }
}
 
Example 10
Source File: ParameterCountInjectComparator.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
private int compareInjectAnnotation(Constructor<?> o1, Constructor<?> o2) {
    boolean hasInject1 = o1.isAnnotationPresent(Inject.class);
    boolean hasInject2 = o2.isAnnotationPresent(Inject.class);
    if (hasInject1 && !hasInject2) {
        return -1;
    }
    else if (hasInject2 && !hasInject1) {
        return 1;
    }
    else {
        return 0;
    }
}
 
Example 11
Source File: ModelClassConstructor.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
public ModelClassConstructor(Constructor<ModelType> constructor, StaticInjectAnnotationProcessorFactory[] processorFactories, DefaultInjectionStrategy defaultInjectionStrategy) {
    this.constructor = constructor;
    this.hasInjectAnnotation = constructor.isAnnotationPresent(Inject.class);

    Type[] parameterTypes = constructor.getGenericParameterTypes();
    this.constructorParametersArray = new ConstructorParameter[parameterTypes.length];

    for (int i = 0; i < parameterTypes.length; i++) {
        Type genericType = ReflectionUtil.mapPrimitiveClasses(parameterTypes[i]);
        boolean isPrimitive = (parameterTypes[i] != genericType);
        this.constructorParametersArray[i] = new ConstructorParameter(
                constructor.getParameterAnnotations()[i], constructor.getParameterTypes()[i], genericType, isPrimitive, i,
                processorFactories, defaultInjectionStrategy);
    }
}
 
Example 12
Source File: TestRandomChains.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
  List<Class<?>> analysisClasses = getClassesForPackage("org.apache.lucene.analysis");
  tokenizers = new ArrayList<>();
  tokenfilters = new ArrayList<>();
  charfilters = new ArrayList<>();
  for (final Class<?> c : analysisClasses) {
    final int modifiers = c.getModifiers();
    if (
      // don't waste time with abstract classes or deprecated known-buggy ones
      Modifier.isAbstract(modifiers) || !Modifier.isPublic(modifiers)
      || c.isSynthetic() || c.isAnonymousClass() || c.isMemberClass() || c.isInterface()
      || c.isAnnotationPresent(Deprecated.class)
      || !(Tokenizer.class.isAssignableFrom(c) || TokenFilter.class.isAssignableFrom(c) || CharFilter.class.isAssignableFrom(c))
    ) {
      continue;
    }
    
    for (final Constructor<?> ctor : c.getConstructors()) {
      // don't test synthetic or deprecated ctors, they likely have known bugs:
      if (ctor.isSynthetic() || ctor.isAnnotationPresent(Deprecated.class) || brokenConstructors.get(ctor) == ALWAYS) {
        continue;
      }
      // conditional filters are tested elsewhere
      if (ConditionalTokenFilter.class.isAssignableFrom(c)) {
        continue;
      }
      if (Tokenizer.class.isAssignableFrom(c)) {
        assertTrue(ctor.toGenericString() + " has unsupported parameter types",
          allowedTokenizerArgs.containsAll(Arrays.asList(ctor.getParameterTypes())));
        tokenizers.add(castConstructor(Tokenizer.class, ctor));
      } else if (TokenFilter.class.isAssignableFrom(c)) {
        assertTrue(ctor.toGenericString() + " has unsupported parameter types",
          allowedTokenFilterArgs.containsAll(Arrays.asList(ctor.getParameterTypes())));
        tokenfilters.add(castConstructor(TokenFilter.class, ctor));
      } else if (CharFilter.class.isAssignableFrom(c)) {
        assertTrue(ctor.toGenericString() + " has unsupported parameter types",
          allowedCharFilterArgs.containsAll(Arrays.asList(ctor.getParameterTypes())));
        charfilters.add(castConstructor(CharFilter.class, ctor));
      } else {
        fail("Cannot get here");
      }
    }
  }
  
  final Comparator<Constructor<?>> ctorComp = (arg0, arg1) -> arg0.toGenericString().compareTo(arg1.toGenericString());
  Collections.sort(tokenizers, ctorComp);
  Collections.sort(tokenfilters, ctorComp);
  Collections.sort(charfilters, ctorComp);
  if (VERBOSE) {
    System.out.println("tokenizers = " + tokenizers);
    System.out.println("tokenfilters = " + tokenfilters);
    System.out.println("charfilters = " + charfilters);
  }
}
 
Example 13
Source File: ConstructorInvocation.java    From android-test with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked") // raw type for constructor can not be avoided
private Object invokeConstructorExplosively(Object... constructorParams) {
  Object returnValue = null;
  Constructor<?> constructor = null;
  ConstructorKey constructorKey = new ConstructorKey(clazz, parameterTypes);
  try {
    // Lookup constructor in cache
    constructor = constructorCache.getIfPresent(constructorKey);
    if (null == constructor) {
      logDebug(
          TAG,
          "Cache miss for constructor: %s(%s). Loading into cache.",
          clazz.getSimpleName(),
          Arrays.toString(constructorParams));
      // Lookup constructor using annotation class
      if (annotationClass != null) {
        for (Constructor<?> candidate : clazz.getDeclaredConstructors()) {
          if (candidate.isAnnotationPresent(annotationClass)) {
            constructor = candidate;
            break;
          }
        }
      }
      // No annotated constructor found. Try constructor lookup by parameter types
      if (null == constructor) {
        constructor = clazz.getConstructor(parameterTypes);
      }

      checkState(
          constructor != null,
          "No constructor found for annotation: %s, or parameter types: %s",
          annotationClass,
          Arrays.asList(parameterTypes));
      constructorCache.put(constructorKey, constructor);
    } else {
      logDebug(
          TAG,
          "Cache hit for constructor: %s(%s).",
          clazz.getSimpleName(),
          Arrays.toString(constructorParams));
    }

    constructor.setAccessible(true);
    returnValue = constructor.newInstance(constructorParams);
  } catch (InvocationTargetException ite) {
    throw new RemoteProtocolException(
        String.format(
            Locale.ROOT,
            "Cannot invoke constructor %s with constructorParams [%s] on clazz %s",
            constructor,
            Arrays.toString(constructorParams),
            clazz.getName()),
        ite);
  } catch (IllegalAccessException iae) {
    throw new RemoteProtocolException(
        String.format(Locale.ROOT, "Cannot create instance of %s", clazz.getName()), iae);
  } catch (InstantiationException ia) {
    throw new RemoteProtocolException(
        String.format(Locale.ROOT, "Cannot create instance of %s", clazz.getName()), ia);
  } catch (NoSuchMethodException nsme) {
    throw new RemoteProtocolException(
        String.format(
            Locale.ROOT,
            "No constructor found for clazz: %s. Available constructors: %s",
            clazz.getName(),
            Arrays.asList(clazz.getConstructors())),
        nsme);
  } catch (SecurityException se) {
    throw new RemoteProtocolException(
        String.format(Locale.ROOT, "Constructor not accessible: %s", constructor.getName()), se);
  } finally {
    logDebug(TAG, "%s(%s)", clazz.getSimpleName(), Arrays.toString(constructorParams));
  }
  return returnValue;
}
 
Example 14
Source File: ConstructorBindingImpl.java    From businessworks with Apache License 2.0 4 votes vote down vote up
/** Returns true if the inject annotation is on the constructor. */
private static boolean hasAtInject(Constructor cxtor) {
  return cxtor.isAnnotationPresent(Inject.class)
      || cxtor.isAnnotationPresent(javax.inject.Inject.class);
}
 
Example 15
Source File: ComponentDescriptor.java    From fenixedu-cms with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean isJsonConstructor(Constructor<?> constructor) {
    return constructor.isAnnotationPresent(DynamicComponent.class) && Stream.of(constructor.getParameterTypes())
            .filter(parameterType -> JsonObject.class.isAssignableFrom(parameterType)).findAny().isPresent();
}
 
Example 16
Source File: DeterministicCodeOptimizer.java    From calcite with Apache License 2.0 3 votes vote down vote up
/**
 * Checks if new instance creation can be reused. For instance {@code new
 * BigInteger("42")} is effectively final and can be reused.
 *
 *
 * @param newExpression method to test
 * @return true when the method is deterministic
 */
protected boolean isConstructorDeterministic(NewExpression newExpression) {
  final Class klass = (Class) newExpression.type;
  final Constructor constructor = getConstructor(klass);
  return allMethodsDeterministic(klass)
      || constructor != null
      && constructor.isAnnotationPresent(Deterministic.class);
}
 
Example 17
Source File: DeterministicCodeOptimizer.java    From Quicksql with MIT License 3 votes vote down vote up
/**
 * Checks if new instance creation can be reused. For instance {@code new
 * BigInteger("42")} is effectively final and can be reused.
 *
 *
 * @param newExpression method to test
 * @return true when the method is deterministic
 */
protected boolean isConstructorDeterministic(NewExpression newExpression) {
  final Class klass = (Class) newExpression.type;
  final Constructor constructor = getConstructor(klass);
  return allMethodsDeterministic(klass)
      || constructor != null
      && constructor.isAnnotationPresent(Deterministic.class);
}