Java Code Examples for java.lang.reflect.Field#getAnnotations()

The following examples show how to use java.lang.reflect.Field#getAnnotations() . 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: CheckInjectionPointUsage.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void validate(final EjbModule ejbModule) {
    if (ejbModule.getBeans() == null) {
        return;
    }

    try {
        for (final Field field : ejbModule.getFinder().findAnnotatedFields(Inject.class)) {
            if (!field.getType().equals(InjectionPoint.class) || !HttpServlet.class.isAssignableFrom(field.getDeclaringClass())) {
                continue;
            }

            final Annotation[] annotations = field.getAnnotations();
            if (annotations.length == 1 || (annotations.length == 2 && field.getAnnotation(Default.class) != null)) {
                throw new DefinitionException("Can't inject InjectionPoint in " + field.getDeclaringClass());
            } // else we should check is there is no other qualifier than @Default but too early
        }
    } catch (final NoClassDefFoundError noClassDefFoundError) {
        // ignored: can't check but maybe it is because of an optional dep so ignore it
        // not important to skip it since the failure will be reported elsewhere
        // this validator doesn't check it
    }
}
 
Example 2
Source File: TestUtils.java    From OpenESPI-DataCustodian-java with Apache License 2.0 6 votes vote down vote up
private static Annotation getAnnotation(Class clazz, String fieldName,
		Class annotationClass) {
	Field field;

	try {
		field = clazz.getDeclaredField(fieldName);
	} catch (NoSuchFieldException e) {
		throw new AssertionError(String.format(
				"'%s' is missing field '%s'", clazz.getCanonicalName(),
				fieldName));
	}

	Annotation foundAnnotation = null;

	for (Annotation annotation : field.getAnnotations()) {
		if (annotation.annotationType().equals(annotationClass)) {
			foundAnnotation = annotation;
			break;
		}
	}

	return foundAnnotation;
}
 
Example 3
Source File: Injector.java    From elemeimitate with Apache License 2.0 6 votes vote down vote up
/**
 * Injects all fields that are marked with the {@link InjectView} annotation.
 * <p>
 * For each field marked with the InjectView annotation, a call to
 * {@link Activity#findViewById(int)} will be made, passing in the resource id stored in the
 * value() method of the InjectView annotation as the int parameter, and the result of this call
 * will be assigned to the field.
 *
 * @throws IllegalStateException if injection fails, common causes being that you have used an
 *             invalid id value, or you haven't called setContentView() on your Activity.
 */
public void inject() {
    for (Field field : mActivity.getClass().getDeclaredFields()) {
        for (Annotation annotation : field.getAnnotations()) {
            if (annotation.annotationType().equals(InjectView.class)) {
                try {
                    Class<?> fieldType = field.getType();
                    int idValue = InjectView.class.cast(annotation).value();
                    field.setAccessible(true);
                    Object injectedValue = fieldType.cast(mActivity.findViewById(idValue));
                    if (injectedValue == null) {
                        throw new IllegalStateException("findViewById(" + idValue
                                + ") gave null for " +
                                field + ", can't inject");
                    }
                    field.set(mActivity, injectedValue);
                    field.setAccessible(false);
                } catch (IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        }
    }
}
 
Example 4
Source File: BeanResourceInfo.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void setParamField(Class<?> cls) {
    if (Object.class == cls || cls == null) {
        return;
    }
    for (Field f : ReflectionUtil.getDeclaredFields(cls)) {
        for (Annotation a : f.getAnnotations()) {
            if (AnnotationUtils.isParamAnnotationClass(a.annotationType())) {
                if (paramFields == null) {
                    paramFields = new ArrayList<>();
                }
                paramsAvailable = true;
                paramFields.add(f);
            }
        }
    }
    setParamField(cls.getSuperclass());
}
 
Example 5
Source File: PersonValidator.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Override
public void validate(Object target, Errors errors) {
	ValidationUtils.rejectIfEmpty(errors, "name", "name.empty");

	List<Field> fileds = getFields(target.getClass());
	for (Field field : fileds) {
		Annotation[] annotations = field.getAnnotations();
		for (Annotation annotation : annotations) {
			if (annotation.annotationType().getAnnotation(Valid.class) != null) {
				try {
					ValidatorRule validatorRule = personValidatorConfig.findRule(annotation);
					if (validatorRule != null) {
						validatorRule.valid(annotation, target, field, errors);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
 
Example 6
Source File: TestUtils.java    From OpenESPI-Common-java with Apache License 2.0 6 votes vote down vote up
private static Annotation getAnnotation(Class clazz, String fieldName,
		Class annotationClass) {
	Field field;

	try {
		field = clazz.getDeclaredField(fieldName);
	} catch (NoSuchFieldException e) {
		throw new AssertionError(String.format(
				"'%s' is missing field '%s'", clazz.getCanonicalName(),
				fieldName));
	}

	Annotation foundAnnotation = null;

	for (Annotation annotation : field.getAnnotations()) {
		if (annotation.annotationType().equals(annotationClass)) {
			foundAnnotation = annotation;
			break;
		}
	}

	return foundAnnotation;
}
 
Example 7
Source File: TestGenerics.java    From yGuard with MIT License 5 votes vote down vote up
public void run(){
    new GenericSignatureFormatError();
    ParameterizedType<MyStringType> pt = new ParameterizedType<MyStringType>();
    pt.add(new MyStringType());
    pt.add(new MyStringType(){});
    for (MyType myType : pt.getList()){
      System.out.println();
      System.out.println("myType " + myType);
      System.out.println("Enclosed by " + myType.getClass().getEnclosingMethod());
      System.out.println("Enclosed by " + myType.getClass().getEnclosingClass().getName());
    }
    
//    Field[] fields = this.getClass().getDeclaredFields();
    for (Field field : this.getClass().getDeclaredFields()){
      System.out.println();
      for (Annotation a : field.getAnnotations()){
        System.out.println(a);
      }
      System.out.println(field);
      System.out.println("generic type " + field.getGenericType());
    }
    
    for (TypeVariable tv : pt.getClass().getTypeParameters()){
      System.out.println();
      System.out.println(tv);
      for (Type t : tv.getBounds()){
        System.out.println("bounds " + t);
      }
    }
  }
 
Example 8
Source File: RuntimeInlineAnnotationReader.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public Annotation[] getAllFieldAnnotations(Field field, Locatable srcPos) {
    Annotation[] r = field.getAnnotations();
    for( int i=0; i<r.length; i++ ) {
        r[i] = LocatableAnnotation.create(r[i],srcPos);
    }
    return r;
}
 
Example 9
Source File: Contexts.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static Collection<Class<?>> findContextFields(final Class<?> cls, final Collection<Class<?>> types) {
    if (cls == Object.class || cls == null) {
        return Collections.emptyList();
    }
    for (final Field f : cls.getDeclaredFields()) {
        for (final Annotation a : f.getAnnotations()) {
            if (a.annotationType() == Context.class || a.annotationType() == Resource.class
                && isContextClass(f.getType())) {
                types.add(f.getType());
            }
        }
    }
    findContextFields(cls.getSuperclass(), types);
    return types;
}
 
Example 10
Source File: Generator.java    From randomizer with Apache License 2.0 5 votes vote down vote up
private Map<Field, Pair<GenerationRule, ConversionAdapter>> createGenerationRules(List<Field> targetAnnotatedFields) {
    Map<Field, Pair<GenerationRule, ConversionAdapter>> generationRules = new LinkedHashMap<>();
    for (Field targetAnnotatedField : targetAnnotatedFields) {
        Annotation[] annotations = targetAnnotatedField.getAnnotations();
        for (Annotation annotation : annotations) {
            if (Reflector.isValidTargetAnnotatedField(annotation.annotationType())) {
                mFieldRuleMapping.put(targetAnnotatedField, getGenerationRulePair(targetAnnotatedField, annotation));
            }
        }
    }
    return generationRules;
}
 
Example 11
Source File: UifFormManager.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Retrieves the session form based on the formkey and updates the non session transient
 * variables on the request form from the session form.
 *
 * @param requestForm
 * @param formKey
 */
public void updateFormWithSession(UifFormBase requestForm, String formKey) {
    UifFormBase sessionForm = sessionForms.get(formKey);
    if (sessionForm == null) {
        return;
    }

    if (!sessionForm.getClass().isAssignableFrom(requestForm.getClass())) {
        throw new RuntimeException(
                "Session form mismatch, session form class not assignable from request form class");
    }

    List<Field> fields = new ArrayList<Field>();
    fields = getAllFields(fields, sessionForm.getClass(), UifFormBase.class);
    for (Field field : fields) {
        boolean copyValue = true;
        for (Annotation an : field.getAnnotations()) {
            if (an instanceof SessionTransient) {
                copyValue = false;
            }
        }

        if (copyValue && ObjectPropertyUtils.isReadableProperty(sessionForm, field.getName()) && ObjectPropertyUtils
                .isWritableProperty(sessionForm, field.getName())) {
            Object fieldValue = ObjectPropertyUtils.getPropertyValue(sessionForm, field.getName());
            ObjectPropertyUtils.setPropertyValue(requestForm, field.getName(), fieldValue);
        }
    }
}
 
Example 12
Source File: Reflector.java    From randomizer with Apache License 2.0 5 votes vote down vote up
static List<Field> getValidTargetAnnotatedFields(Class<?> clazz) {
    List<Field> targetFields = new ArrayList<>();
    List<Field> allTargetFields = getAllTargetFields(clazz);
    for (Field field : allTargetFields) {
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (isValidTargetAnnotatedField(annotation.annotationType())) {
                targetFields.add(field);
                break;
            }
        }
    }
    return targetFields;
}
 
Example 13
Source File: InjectedApplication.java    From android-arscblamer with Apache License 2.0 5 votes vote down vote up
private Collection<Annotation> getBindingAnnotations(Field field) {
  List<Annotation> result = new ArrayList<>();
  for (Annotation annotation : field.getAnnotations()) {
    if (annotation.annotationType().isAnnotationPresent(BindingAnnotation.class)) {
      result.add(annotation);
    }
  }
  return result;
}
 
Example 14
Source File: TypeRenderUtils.java    From arthas with Apache License 2.0 5 votes vote down vote up
public static Element drawField(Class<?> clazz, Integer expand) {
    TableElement fieldsTable = new TableElement(1).leftCellPadding(0).rightCellPadding(0);
    Field[] fields = clazz.getDeclaredFields();
    if (fields == null || fields.length == 0) {
        return fieldsTable;
    }

    for (Field field : fields) {
        TableElement fieldTable = new TableElement().leftCellPadding(0).rightCellPadding(1);
        fieldTable.row("name", field.getName())
                .row("type", StringUtils.classname(field.getType()))
                .row("modifier", StringUtils.modifier(field.getModifiers(), ','));

        Annotation[] annotations = field.getAnnotations();
        if (annotations != null && annotations.length > 0) {
            fieldTable.row("annotation", drawAnnotation(annotations));
        }

        if (Modifier.isStatic(field.getModifiers())) {
            fieldTable.row("value", drawFieldValue(field, expand));
        }

        fieldTable.row(label(""));
        fieldsTable.row(fieldTable);
    }

    return fieldsTable;
}
 
Example 15
Source File: ExecuteMethodValidatorChecker.java    From lastaflute with Apache License 2.0 5 votes vote down vote up
protected void detectLonelyAnnotatedField(Field field, Class<?> beanType, Map<String, Class<?>> genericMap) {
    final boolean hasNestedBeanAnnotation = hasNestedBeanAnnotation(field);
    final BeanDesc beanDesc = getNestedBeanDesc(field, beanType);
    for (int i = 0; i < beanDesc.getFieldSize(); i++) {
        final Field nestedField = beanDesc.getField(i);
        if (!hasNestedBeanAnnotation) {
            for (Annotation anno : nestedField.getAnnotations()) {
                if (isValidatorAnnotation(anno.annotationType())) {
                    throwLonelyValidatorAnnotationException(field, nestedField); // only first level
                }
            }
        }
        doCheckLonelyValidatorAnnotation(nestedField, deriveFieldType(nestedField, genericMap)); // recursive call
    }
}
 
Example 16
Source File: TypeUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Annotation getXmlAttributeAnnotation(Field f) {
    for (Annotation ann : f.getAnnotations()) {
        if (ann.annotationType().getName().equals(Constants.XML_ATTRIBUTE)) {
            return ann;
        }
    }
    return null;
}
 
Example 17
Source File: TypeDescriptor.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Create a new type descriptor from a {@link Field}.
 * <p>Use this constructor when a source or target conversion point is a field.
 * @param field the field
 */
public TypeDescriptor(Field field) {
	this.resolvableType = ResolvableType.forField(field);
	this.type = this.resolvableType.resolve(field.getType());
	this.annotatedElement = new AnnotatedElementAdapter(field.getAnnotations());
}
 
Example 18
Source File: StoreLoader.java    From geowave with Apache License 2.0 4 votes vote down vote up
/**
 * Attempt to load the data store configuration from the config file.
 *
 * @param configFile
 * @return {@code true} if the configuration was successfully loaded
 */
public boolean loadFromConfig(
    final Properties props,
    final String namespace,
    final File configFile,
    final Console console) {

  dataStorePlugin = new DataStorePluginOptions();

  // load all plugin options and initialize dataStorePlugin with type and
  // options
  if (!dataStorePlugin.load(props, namespace)) {
    return false;
  }

  // knowing the datastore plugin options and class type, get all fields
  // and parameters in order to detect which are password fields
  if ((configFile != null) && (dataStorePlugin.getFactoryOptions() != null)) {
    File tokenFile = SecurityUtils.getFormattedTokenKeyFileForConfig(configFile);
    final Field[] fields = dataStorePlugin.getFactoryOptions().getClass().getDeclaredFields();
    for (final Field field : fields) {
      for (final Annotation annotation : field.getAnnotations()) {
        if (annotation.annotationType() == Parameter.class) {
          final Parameter parameter = (Parameter) annotation;
          if (JCommanderParameterUtils.isPassword(parameter)) {
            final String storeFieldName =
                ((namespace != null) && !"".equals(namespace.trim()))
                    ? namespace + "." + DefaultPluginOptions.OPTS + "." + field.getName()
                    : field.getName();
            if (props.containsKey(storeFieldName)) {
              final String value = props.getProperty(storeFieldName);
              String decryptedValue = value;
              try {
                decryptedValue =
                    SecurityUtils.decryptHexEncodedValue(
                        value,
                        tokenFile.getAbsolutePath(),
                        console);
              } catch (final Exception e) {
                LOGGER.error(
                    "An error occurred encrypting specified password value: "
                        + e.getLocalizedMessage(),
                    e);
              }
              props.setProperty(storeFieldName, decryptedValue);
            }
          }
        }
      }
    }
    tokenFile = null;
  }
  // reload datastore plugin with new password-encrypted properties
  if (!dataStorePlugin.load(props, namespace)) {
    return false;
  }

  return true;
}
 
Example 19
Source File: AbstractAnySearchDAO.java    From syncope with Apache License 2.0 4 votes vote down vote up
protected Triple<PlainSchema, PlainAttrValue, AnyCond> check(final AnyCond cond, final AnyTypeKind kind) {
    AnyCond computed = new AnyCond(cond.getType());
    computed.setSchema(cond.getSchema());
    computed.setExpression(cond.getExpression());

    AnyUtils anyUtils = anyUtilsFactory.getInstance(kind);

    Field anyField = anyUtils.getField(computed.getSchema());
    if (anyField == null) {
        LOG.warn("Ignoring invalid field '{}'", computed.getSchema());
        throw new IllegalArgumentException();
    }
    // Keeps track of difference between entity's getKey() and JPA @Id fields
    if ("key".equals(computed.getSchema())) {
        computed.setSchema("id");
    }

    PlainSchema schema = entityFactory.newEntity(PlainSchema.class);
    schema.setKey(anyField.getName());
    for (AttrSchemaType attrSchemaType : AttrSchemaType.values()) {
        if (anyField.getType().isAssignableFrom(attrSchemaType.getType())) {
            schema.setType(attrSchemaType);
        }
    }

    // Deal with any Integer fields logically mapping to boolean values
    boolean foundBooleanMin = false;
    boolean foundBooleanMax = false;
    if (Integer.class.equals(anyField.getType())) {
        for (Annotation annotation : anyField.getAnnotations()) {
            if (Min.class.equals(annotation.annotationType())) {
                foundBooleanMin = ((Min) annotation).value() == 0;
            } else if (Max.class.equals(annotation.annotationType())) {
                foundBooleanMax = ((Max) annotation).value() == 1;
            }
        }
    }
    if (foundBooleanMin && foundBooleanMax) {
        schema.setType(AttrSchemaType.Boolean);
    }

    // Deal with any fields representing relationships to other entities
    if (ArrayUtils.contains(RELATIONSHIP_FIELDS, computed.getSchema())) {
        computed.setSchema(computed.getSchema() + "_id");
        schema.setType(AttrSchemaType.String);
    }

    PlainAttrValue attrValue = anyUtils.newPlainAttrValue();
    if (computed.getType() != AttrCond.Type.LIKE
            && computed.getType() != AttrCond.Type.ILIKE
            && computed.getType() != AttrCond.Type.ISNULL
            && computed.getType() != AttrCond.Type.ISNOTNULL) {

        try {
            ((JPAPlainSchema) schema).validator().validate(computed.getExpression(), attrValue);
        } catch (ValidationException e) {
            LOG.error("Could not validate expression '" + computed.getExpression() + '\'', e);
            throw new IllegalArgumentException();
        }
    }

    return Triple.of(schema, attrValue, computed);
}
 
Example 20
Source File: TypeDescriptor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a new type descriptor from a {@link Field}.
 * <p>Use this constructor when a source or target conversion point is a field.
 * @param field the field
 */
public TypeDescriptor(Field field) {
	this.resolvableType = ResolvableType.forField(field);
	this.type = this.resolvableType.resolve(field.getType());
	this.annotatedElement = new AnnotatedElementAdapter(field.getAnnotations());
}