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

The following examples show how to use java.lang.reflect.Constructor#isAnnotationPresent() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
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
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 Project: JavaTutorial   File: AConstructorProcess.java    License: 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 Project: oxygen   File: ClassUtils.java    License: 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
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 6
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 7
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 8
Source Project: Poseidon   File: DatasourceValidator.java    License: 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
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 10
private Constructor<?> getCustomCtor(Class<?> type) {
    for (Constructor<?> ctor : type.getDeclaredConstructors()) {
        if (ctor.isAnnotationPresent(DynamicComponent.class) && !isJsonConstructor(ctor)) {
            return ctor;
        }
    }
    return ClassUtils.getConstructorIfAvailable(type);
}
 
Example 11
Source Project: base-framework   File: ReflectionUtils.java    License: 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 12
/** 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 13
Source Project: lucene-solr   File: TestRandomChains.java    License: 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 14
@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 15
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 Project: Quicksql   File: DeterministicCodeOptimizer.java    License: 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);
}
 
Example 17
/**
 * 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);
}