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

The following are Jave code examples for showing how to use getAnnotations() of the java.lang.reflect.Field class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: buildAPKsSamples   File: Injector.java   View Source Code Vote up 7 votes
/**
 * 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 2
Project: elasticsearch_my   File: InjectionPoint.java   View Source Code Vote up 6 votes
InjectionPoint(TypeLiteral<?> type, Field field) {
    this.member = field;

    Inject inject = field.getAnnotation(Inject.class);
    this.optional = inject.optional();

    Annotation[] annotations = field.getAnnotations();

    Errors errors = new Errors(field);
    Key<?> key = null;
    try {
        key = Annotations.getKey(type.getFieldType(field), field, annotations, errors);
    } catch (ErrorsException e) {
        errors.merge(e.getErrors());
    }
    errors.throwConfigurationExceptionIfErrorsExist();

    this.dependencies = Collections.<Dependency<?>>singletonList(
        newDependency(key, Nullability.allowsNull(annotations), -1));
}
 
Example 3
Project: jsouplib   File: ClassReader.java   View Source Code Vote up 6 votes
private static List<Resource> getFields(Map<String, Type> lookup, Class clazz, boolean includingPrivate) {
    ArrayList<Resource> resources = new ArrayList<Resource>();
    for (Field field : ReflectKit.getAllFields(clazz, includingPrivate)) {
        Annotation[] annotations = field.getAnnotations();
        if (annotations ==null||annotations.length==0) {//排除未注解变量
            continue;
        }
        if (Modifier.isStatic(field.getModifiers())) {  //去掉 static  变量
            continue;
        }
        if (Modifier.isTransient(field.getModifiers())) {
            continue;
        }
        if (!includingPrivate && !Modifier.isPublic(field.getType().getModifiers())) {
            continue;
        }
        if (includingPrivate) {
            field.setAccessible(true);
        }
        Resource resource = createBindingFromField(lookup, clazz, field);
        resources.add(resource);
    }
    return resources;
}
 
Example 4
Project: Gesture   File: GestureEngine.java   View Source Code Vote up 6 votes
private void parseAnnotation(Object target) {
    ArrayMap map = new ArrayMap();
    Class<?> targetClass = target.getClass();
    Field[] fields = targetClass.getDeclaredFields();
    for (Field field : fields) {
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof TurnLeftSideslip) {
                map.put("TurnLeftSideslip", annotation);
            } else if (annotation instanceof TurnRightSideslip) {
                map.put("TurnRightSideslip", annotation);
            } else if (annotation instanceof LongTouch) {
                map.put("LongTouch", annotation);
            } else if (annotation instanceof Drag) {
                map.put("Drag", annotation);
            }
        }
    }
    itemListener.setLimitMap(map);
}
 
Example 5
Project: Elasticsearch   File: InjectionPoint.java   View Source Code Vote up 6 votes
InjectionPoint(TypeLiteral<?> type, Field field) {
    this.member = field;

    Inject inject = field.getAnnotation(Inject.class);
    this.optional = inject.optional();

    Annotation[] annotations = field.getAnnotations();

    Errors errors = new Errors(field);
    Key<?> key = null;
    try {
        key = Annotations.getKey(type.getFieldType(field), field, annotations, errors);
    } catch (ErrorsException e) {
        errors.merge(e.getErrors());
    }
    errors.throwConfigurationExceptionIfErrorsExist();

    this.dependencies = Collections.<Dependency<?>>singletonList(
        newDependency(key, Nullability.allowsNull(annotations), -1));
}
 
Example 6
Project: BlockBall   File: YamlSerializer.java   View Source Code Vote up 6 votes
/**
 * Returns all annotationWrappers from a class to resolve the order
 *
 * @param sourceClass sourceClass
 * @return annotationWrappers
 */
private static List<AnnotationWrapper> getOrderedAnnotations(Class<?> sourceClass) {
    final List<AnnotationWrapper> annotationWrappers = new ArrayList<>();
    Class<?> clazz = sourceClass;
    while (clazz != null) {
        for (final Field field : clazz.getDeclaredFields()) {
            for (final Annotation annotation : field.getAnnotations()) {
                if (annotation.annotationType() == YamlSerialize.class) {
                    annotationWrappers.add(new AnnotationWrapper((YamlSerialize) annotation, field));
                }
            }
        }
        clazz = clazz.getSuperclass();
    }
    annotationWrappers.sort((o1, o2) -> {
        if (o1.annotation.orderNumber() > o2.annotation.orderNumber())
            return 1;
        else if (o1.annotation.orderNumber() < o2.annotation.orderNumber())
            return -1;
        return 0;
    });
    return annotationWrappers;
}
 
Example 7
Project: openjdk-jdk10   File: HotSpotResolvedJavaFieldImpl.java   View Source Code Vote up 5 votes
@Override
public Annotation[] getAnnotations() {
    Field javaField = toJava();
    if (javaField != null) {
        return javaField.getAnnotations();
    }
    return new Annotation[0];
}
 
Example 8
Project: openjdk-jdk10   File: RuntimeInlineAnnotationReader.java   View Source Code Vote up 5 votes
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
Project: javadoc2swagger   File: DefinitionParser.java   View Source Code Vote up 5 votes
/**
 * Processes all fields of a class
 * 
 * @param fields
 *            array of fields
 * @param definition
 *            current definition
 * @param rootDefinition
 *            definition where the recursion started to prevent an endless
 *            loop
 * @return list of {@link Property} objects
 * @throws ParserException
 *             Error while the parsing process
 */
public List<Property> processFields(Field[] fields, Definition definition, Definition rootDefinition)
        throws ParserException {
    DataTypeFactory typeHandler = new DataTypeFactory();
    List<Property> properties = new ArrayList<>();
    for (Field field : fields) {
        if (field.getAnnotation(JsonIgnore.class) == null && field.getAnnotation(JsonBackReference.class) == null) {
            Property property = new Property();
            Class<?> typeClass = field.getType();
            Annotation[] annotations = field.getAnnotations();
            Type genericType = field.getGenericType();
            processGenerics(genericType, property, definition, rootDefinition);
            DataType typeObject = typeHandler.getDataType(typeClass.getName());
            String type = typeObject.getType();
            String name = field.getName();
            property.setName(name);
            if (type.length() > 14 && (type.substring(14).equals(definition.getClassName())
                    || type.substring(14).equals(rootDefinition.getClassName()))) {
                property.setReference(type);
            } else if (type.startsWith("#")) {
                createDefinitionBySchemaAndPackageIfNotExists(type, typeClass.getTypeName(), rootDefinition);
                property.setReference(type);
            } else {
                property.setType(type);
                property.setFormat(typeObject.getFormat());
            }
            properties.add(property);
            processAnnotations(annotations, definition, name);
        }
    }
    return properties;
}
 
Example 10
Project: GPigValidator   File: Validator.java   View Source Code Vote up 5 votes
private static boolean isCorrectFieldForAnnotations(Object objectToValidate, Field field) {
    boolean result = true;
    for (Annotation annotation : field.getAnnotations())
        result &= isAnnotationConstraintCorrect(objectToValidate, field, annotation);

    return result;
}
 
Example 11
Project: rocketmq-spring-boot-starter   File: AbstractMQProducer.java   View Source Code Vote up 5 votes
private Message genMessage(String topic, String tag, Object msgObj) {
    String messageKey= "";
    try {
        Field[] fields = msgObj.getClass().getDeclaredFields();
        for (Field field : fields) {
            Annotation[] allFAnnos= field.getAnnotations();
            if(allFAnnos.length > 0) {
                for (int i = 0; i < allFAnnos.length; i++) {
                    if(allFAnnos[i].annotationType().equals(MQKey.class)) {
                        field.setAccessible(true);
                        MQKey mqKey = MQKey.class.cast(allFAnnos[i]);
                        messageKey = StringUtils.isEmpty(mqKey.prefix()) ? field.get(msgObj).toString() : (mqKey.prefix() + field.get(msgObj).toString());
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("parse key error : {}" , e.getMessage());
    }
    String str = gson.toJson(msgObj);
    if(StringUtils.isEmpty(topic)) {
        if(StringUtils.isEmpty(getTopic())) {
            throw new RuntimeException("no topic defined to send this message");
        }
        topic = getTopic();
    }
    Message message = new Message(topic, str.getBytes(Charset.forName("utf-8")));
    if (!StringUtils.isEmpty(tag)) {
        message.setTags(tag);
    } else if (!StringUtils.isEmpty(getTag())) {
        message.setTags(getTag());
    }
    if(StringUtils.isNotEmpty(messageKey)) {
        message.setKeys(messageKey);
    }
    return message;
}
 
Example 12
Project: jsouplib   File: ClassReader.java   View Source Code Vote up 5 votes
private static Resource createBindingFromField(Map<String, Type> lookup, Class clazz, Field field) {
    try {
        Resource resource = new Resource(clazz, lookup, field.getGenericType());
        resource.fromNames = new String[]{field.getName()};
        resource.name = field.getName();
        resource.annotations = field.getAnnotations();
        resource.field = field;
        return resource;
    } catch (Exception e) {
        throw new RuntimeException("failed to onAttachView resource for field: " + field, e);
    }
}
 
Example 13
Project: holon-core   File: DefaultBeanIntrospector.java   View Source Code Vote up 5 votes
/**
 * Build a {@link BeanProperty} instance using given {@link PropertyDescriptor}.
 * @param beanClass Bean class
 * @param parentPath Optional parent path
 * @param parent Parent bean property if bean class is a nested bean class
 * @param propertyDescriptor Bean property descriptor
 * @return BeanProperty instance
 * @throws BeanIntrospectionException Error introspecting bean class
 */
private Optional<BeanProperty<?>> buildBeanProperty(Class<?> beanClass, Path<?> parentPath, BeanProperty<?> parent,
		PropertyDescriptor propertyDescriptor) throws BeanIntrospectionException {
	// annotations
	Annotation[] annotations = null;
	Field propertyField = findDeclaredField(beanClass, propertyDescriptor.getName());
	if (propertyField != null) {
		// check ignore
		if (propertyField.isAnnotationPresent(Ignore.class)) {
			LOGGER.debug(() -> "Bean class [" + beanClass + "] - Property " + propertyDescriptor.getName()
					+ " ignored according to IgnoreProperty annotation ");
			return Optional.empty();
		}

		annotations = propertyField.getAnnotations();
	}

	BeanProperty.Builder<?> property = BeanProperty
			.builder(propertyDescriptor.getName(), propertyDescriptor.getPropertyType()).parent(parent)
			.readMethod(propertyDescriptor.getReadMethod()).writeMethod(propertyDescriptor.getWriteMethod())
			.field(propertyField).annotations(annotations);

	if (parent == null && parentPath != null) {
		property.parent(parentPath);
	}

	// post processors
	property = postProcessBeanProperty(property, beanClass);

	return Optional.of(property);

}
 
Example 14
Project: OpenJSharp   File: RuntimeInlineAnnotationReader.java   View Source Code Vote up 5 votes
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 15
Project: sirocco   File: FieldSupport.java   View Source Code Vote up 5 votes
public static Annotation[] getAnnotations(Field f, Class<?> filterBy, boolean inherits)
{
	ArrayList<Annotation> filteredAnns = new ArrayList<Annotation>();
	
	Annotation[] allAnns = (inherits ? f.getAnnotations() : f.getDeclaredAnnotations());
	
	for (Annotation ann : allAnns) {
		if (filterBy.isAssignableFrom(ann.annotationType()))
			filteredAnns.add(ann);
	}
	return allAnns;
	
}
 
Example 16
Project: dummymaker   File: AnnotationScanner.java   View Source Code Vote up 5 votes
@Override
public Map<Field, Set<Annotation>> scan(final Class t) {
    final Map<Field, Set<Annotation>> classFieldAnnotations = new HashMap<>();

    try {
        for(final Field field : t.getDeclaredFields()) {
            for(final Annotation annotation : field.getAnnotations()) {
                final Set<Annotation> annotatedField = classFieldAnnotations.putIfAbsent(field, createNode(annotation));

                if(annotatedField != null) {
                    annotatedField.add(annotation);
                    classFieldAnnotations.replace(field, annotatedField);
                }

                for(Annotation primeAnnotation : annotation.annotationType().getDeclaredAnnotations()) {
                    final Set<Annotation> fieldPrimeAnnotated = classFieldAnnotations.putIfAbsent(field, createNode(primeAnnotation));

                    if(fieldPrimeAnnotated != null) {
                        fieldPrimeAnnotated.add(primeAnnotation);
                        classFieldAnnotations.replace(field, fieldPrimeAnnotated);
                    }
                }
            }
        }
    } catch (SecurityException e) {
        logger.warning(e.toString());
    }

    return classFieldAnnotations;
}
 
Example 17
Project: excel-util4j   File: AnnotationFactory.java   View Source Code Vote up 5 votes
/**
 * 通过Field获取Annotation[]
 *
 * @param field <p>需要获取注解列表的属性</p>
 *              <p>建议field通过FieldFactory获取</p>
 * @return
 */
public static Annotation[] getAnnotations(Field field) {

    Annotation[] annos = annoCache.get(field);
    if (annos == null) {
        annos = field.getAnnotations();
        annoCache.put(field, annos);
    }

    return annos;
}
 
Example 18
Project: android-training-2017   File: SqlConnector.java   View Source Code Vote up 4 votes
private void createTables(final SQLiteDatabase readableConnection, final Class<?>[] tableClassArray) {

        readableConnection.beginTransaction();

        try {
            for (final Class<?> tableClass : tableClassArray) {
                final dbTable dbTableAnnotation = tableClass.getAnnotation(dbTable.class);
                if (dbTableAnnotation != null) {
                    final String dbTableName = dbTableAnnotation.value();

                    if (TextUtils.isEmpty(dbTableName)) {
                        return;
                    }

                    final StringBuilder stringBuilder = new StringBuilder();

                    final Field[] fields = tableClass.getFields();
                    final int fieldCount = fields.length;
                    for (int i = 0; i < fieldCount; i++) {
                        final Field field = fields[i];
                        final Annotation[] fieldAnnotations = field.getAnnotations();
                        final String fieldName = (String) field.get(null);
                        String fieldType = null;

                        for (final Annotation fieldAnnotation : fieldAnnotations) {
                            final Class<?> fieldAnnotationType = fieldAnnotation.annotationType();
                            if (fieldAnnotationType.equals(dbString.class)) {
                                fieldType = ((dbString) fieldAnnotation).value();
                            } else if (fieldAnnotationType.equals(dbLong.class)) {
                                fieldType = ((dbLong) fieldAnnotation).value();
                            } else if (fieldAnnotationType.equals(dbInteger.class)) {
                                fieldType = ((dbInteger) fieldAnnotation).value();
                            }
                            if (!TextUtils.isEmpty(fieldType)) {
                                stringBuilder.append(fieldName + " " + fieldType + ",");
                            }
                        }

                    }

                    //TODO think about solution if last field marked some annotation;
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1);

                    final String tableCreteQuery = String.format(TABLE_TEMPLATE, dbTableName, stringBuilder.toString());
                    readableConnection.execSQL(tableCreteQuery);
                    Log.d(TAG, "createTables() returned: " + tableCreteQuery);
                }
            }
            readableConnection.setTransactionSuccessful();
        } catch (final Exception e) {
            Log.e(TAG, "create table exception", e);
        } finally {
            readableConnection.endTransaction();
        }

    }
 
Example 19
Project: minijax   File: MinijaxFieldDescriptor.java   View Source Code Vote up 4 votes
public MinijaxFieldDescriptor(final Field field) {
    super(field.getDeclaringClass(), field.getAnnotatedType(), field.getAnnotations());
    this.field = field;
}
 
Example 20
Project: headb   File: HeaCore.java   View Source Code Vote up 4 votes
private void initEntity(Class<?> clazz, String entityName, long entityLastModified) {
	logger.info(HLogUtils.format("初始化", entityName));
	Entity entity = new Entity();
	entity.setLastModified(entityLastModified);
	entity.setEntityName(entityName);
	String tableName=HOrmUtil.toSql(entityName);
	HeaEntity heaEntity= clazz.getAnnotation(HeaEntity.class);
	if(null!=heaEntity){
		if(HStringUtils.isNotNull(heaEntity.value())){
			tableName=heaEntity.value();
		}
	}
	entity.setTableName(tableName);
	Field[] fileds = clazz.getDeclaredFields();// 只有本类
	Map<String, EntityField> entityFieldMap = new HHashMap<String, EntityField>();
	for (Field field : fileds) {
		EntityField entityField = new EntityField();
		String fieldName = field.getName();
		entityField.setFieldName(fieldName);
		String columnName = HOrmUtil.toSql(fieldName);	
		Class<?> type = field.getType();
		entityField.setColumnName(columnName);
		entityField.setTypeName(type.getSimpleName());
		Boolean isBaseType = HClassUtils.isBaseType(type);
		entityField.setIsBaseType(isBaseType);
		if (isBaseType) {
			entityField.setIsColumn(true);
		}
		Annotation[] annotations = field.getAnnotations();
		for (Annotation annotation : annotations) {
			if (annotation instanceof HeaId) {
				entityField.setIsId(true);
				entity.setIdFieldName(fieldName);
				entity.setIdColumnName(columnName);
				entity.setIdType(type.getSimpleName());
				boolean auto = ((HeaId) annotation).auto();
				if (auto) {
					if (type.getSimpleName().equals("String")) {
						entity.setIdModel(HeaConstant.Entity.UUID);
					} else {
						entity.setIdModel(HeaConstant.Entity.INCID);
					}
				}
			}
			if (annotation instanceof HeaExclusion) {
				entityField.setIsColumn(false);
			}
		}
		entityFieldMap.put(fieldName, entityField);
	}
	entity.setFieldMap(entityFieldMap);
	entityMap.put(entityName, entity);
}