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

The following examples show how to use java.lang.reflect.Field#getAnnotations() . 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 check out the related API usage on the sidebar.
Example 1
Source Project: OpenESPI-Common-java   File: TestUtils.java    License: 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 2
Source Project: tomee   File: CheckInjectionPointUsage.java    License: 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 3
@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 4
Source Project: cxf   File: BeanResourceInfo.java    License: 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 Project: elemeimitate   File: Injector.java    License: 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 6
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
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 8
/**
 * 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 9
Source Project: randomizer   File: Generator.java    License: 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 10
Source Project: yGuard   File: TestGenerics.java    License: 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 11
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 12
Source Project: tomee   File: Contexts.java    License: 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 13
Source Project: randomizer   File: Reflector.java    License: 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 14
Source Project: arthas   File: TypeRenderUtils.java    License: 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
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 Project: netbeans   File: TypeUtil.java    License: 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 Project: java-technology-stack   File: TypeDescriptor.java    License: 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 Project: geowave   File: StoreLoader.java    License: 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 Project: syncope   File: AbstractAnySearchDAO.java    License: 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
/**
 * 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());
}