Java Code Examples for java.lang.reflect.Field#getDeclaredAnnotations()
The following examples show how to use
java.lang.reflect.Field#getDeclaredAnnotations() .
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: Morpheus File: Mapper.java License: MIT License | 6 votes |
/** * Get the annotated relationship names. * * @param clazz Class for annotation. * @return List of relationship names. */ private HashMap<String, String> getRelationshipNames(Class clazz) { HashMap<String, String> relationNames = new HashMap<>(); for (Field field : clazz.getDeclaredFields()) { String fieldName = field.getName(); for (Annotation annotation : field.getDeclaredAnnotations()) { if (annotation.annotationType() == SerializedName.class) { SerializedName serializeName = (SerializedName)annotation; fieldName = serializeName.value(); } if (annotation.annotationType() == Relationship.class) { Relationship relationshipAnnotation = (Relationship)annotation; relationNames.put(relationshipAnnotation.value(), fieldName); } } } return relationNames; }
Example 2
Source Project: MVPAndroidBootstrap File: ReflectionHelper.java License: Apache License 2.0 | 6 votes |
private static Map<Class<? extends Annotation>, List<Field>> groupFieldsByAnnotation(Field[] fields) { HashMap<Class<? extends Annotation>, List<Field>> groupedFields = new HashMap<Class<? extends Annotation>, List<Field>>(); for (Field field : fields) { for (Annotation a : field.getDeclaredAnnotations()) { List<Field> fieldsForAnnotation = groupedFields.get(a.annotationType()); if (fieldsForAnnotation == null) { fieldsForAnnotation = new ArrayList<Field>(); } fieldsForAnnotation.add(field); groupedFields.put(a.annotationType(), fieldsForAnnotation); } } return groupedFields; }
Example 3
Source Project: sundrio File: ClassTo.java License: Apache License 2.0 | 6 votes |
private static Set<Property> getProperties(Class item) { Set<Property> properties = new HashSet<Property>(); for (Field field : item.getDeclaredFields()) { List<AnnotationRef> annotationRefs = new ArrayList<AnnotationRef>(); for (Annotation annotation : field.getDeclaredAnnotations()) { annotationRefs.add(ANNOTATIONTYPEREF.apply(annotation.annotationType())); } field.getDeclaringClass(); properties.add(new PropertyBuilder() .withName(field.getName()) .withModifiers(field.getModifiers()) .withAnnotations(annotationRefs) .withTypeRef(TYPEREF.apply(field.getGenericType())) .build()); } return properties; }
Example 4
Source Project: EChartsAnnotation File: EChartsAnnotationProcessor.java License: MIT License | 6 votes |
/** * 主解析方法 * 解析注解并附加到已有的JSON树(继承) * @param head JSON树的根 * @param object 被解析的类 * @return 合并后的JSON树根 */ private Map<String,Object> parse(Map<String,Object> head,@NotNull Object object){ Class clazz=object.getClass(); Field[] fields=clazz.getDeclaredFields(); for(Field field:fields) { Object value=getFieldValue(field,object); Annotation[] annotations=field.getDeclaredAnnotations(); for(Annotation an:annotations){ if(!checkClass(an))continue; if(value==null) addAnnotationToMap(head,an,getAnnotationValue(an)); else addAnnotationToMap(head,an,value); } } return head; }
Example 5
Source Project: RxAndroidBootstrap File: ReflectionHelper.java License: Apache License 2.0 | 6 votes |
private static Map<Class<? extends Annotation>, List<Field>> groupFieldsByAnnotation(Field[] fields) { HashMap<Class<? extends Annotation>, List<Field>> groupedFields = new HashMap<Class<? extends Annotation>, List<Field>>(); for (Field field : fields) { for (Annotation a : field.getDeclaredAnnotations()) { List<Field> fieldsForAnnotation = groupedFields.get(a.annotationType()); if (fieldsForAnnotation == null) { fieldsForAnnotation = new ArrayList<Field>(); } fieldsForAnnotation.add(field); groupedFields.put(a.annotationType(), fieldsForAnnotation); } } return groupedFields; }
Example 6
Source Project: glitr File: TypeRegistry.java License: MIT License | 6 votes |
private GraphQLOutputType getGraphQLOutputTypeFromAnnotationsOnField(Class declaringClass, Method method, GraphQLOutputType graphQLOutputType, String name) { Field field = ReflectionUtil.getFieldByName(declaringClass, name); if (field != null) { Annotation[] fieldAnnotations = field.getDeclaredAnnotations(); for (Annotation annotation: fieldAnnotations) { // custom OutputType if (annotationToGraphQLOutputTypeMap.containsKey(annotation.annotationType())) { Func5<TypeRegistry, Field, Method, Class, Annotation, GraphQLOutputType> customGraphQLOutputTypeFunc = annotationToGraphQLOutputTypeMap.get(annotation.annotationType()); GraphQLOutputType outputType = customGraphQLOutputTypeFunc.call(this, field, method, declaringClass, annotation); if (outputType != null) { graphQLOutputType = outputType; break; } } } } return graphQLOutputType; }
Example 7
Source Project: photoviewer File: PreferencesDao.java License: Apache License 2.0 | 6 votes |
private void handleField(Field field) { Annotation[] annotations = field.getDeclaredAnnotations(); for(Annotation annotation : annotations) { if(annotation.annotationType().isAssignableFrom(Preference.class)) { Preference preferenceAnnotation = (Preference) annotation; if (!preferenceAnnotation.enabled()) { return; } if (!preferenceAnnotation.name().isEmpty()) { mFieldsPreferencesMap.put(preferenceAnnotation.name(), field); return; } } } mFieldsPreferencesMap.put(field.getName(), field); }
Example 8
Source Project: byte-buddy File: FieldDescriptionLatentTest.java License: Apache License 2.0 | 5 votes |
protected FieldDescription.InDefinedShape describe(Field field) { return new FieldDescription.Latent(TypeDescription.ForLoadedType.of(field.getDeclaringClass()), field.getName(), field.getModifiers(), TypeDefinition.Sort.describe(field.getGenericType()), new AnnotationList.ForLoadedAnnotations(field.getDeclaredAnnotations())); }
Example 9
Source Project: restcommander File: Validation.java License: Apache License 2.0 | 5 votes |
static void searchValidator(Class<?> clazz, String name, Map<String, List<Validator>> result) { for (Field field : clazz.getDeclaredFields()) { List<Validator> validators = new ArrayList<Validator>(); String key = name + "." + field.getName(); boolean containsAtValid = false; for (Annotation annotation : field.getDeclaredAnnotations()) { if (annotation.annotationType().getName().startsWith("play.data.validation")) { Validator validator = new Validator(annotation); validators.add(validator); if (annotation.annotationType().equals(Equals.class)) { validator.params.put("equalsTo", name + "." + ((Equals) annotation).value()); } if (annotation.annotationType().equals(InFuture.class)) { validator.params.put("reference", ((InFuture) annotation).value()); } if (annotation.annotationType().equals(InPast.class)) { validator.params.put("reference", ((InPast) annotation).value()); } } if (annotation.annotationType().equals(Valid.class)) { containsAtValid = true; } } if (!validators.isEmpty()) { result.put(key, validators); } if (containsAtValid) { searchValidator(field.getType(), key, result); } } }
Example 10
Source Project: quarkus File: CreateMockitoMocksCallback.java License: Apache License 2.0 | 5 votes |
static Annotation[] getQualifiers(Field fieldToMock) { List<Annotation> qualifiers = new ArrayList<>(); Annotation[] fieldAnnotations = fieldToMock.getDeclaredAnnotations(); for (Annotation fieldAnnotation : fieldAnnotations) { for (Annotation annotationOfFieldAnnotation : fieldAnnotation.annotationType().getAnnotations()) { if (annotationOfFieldAnnotation.annotationType().equals(Qualifier.class)) { qualifiers.add(fieldAnnotation); break; } } } return qualifiers.toArray(new Annotation[0]); }
Example 11
Source Project: everrest File: FieldInjectorImpl.java License: Eclipse Public License 2.0 | 5 votes |
/** * @param field * java.lang.reflect.Field */ public FieldInjectorImpl(Field field, ParameterResolverFactory parameterResolverFactory) { this.field = field; this.parameterResolverFactory = parameterResolverFactory; this.annotations = field.getDeclaredAnnotations(); final Class<?> declaringClass = field.getDeclaringClass(); this.setter = getSetter(declaringClass, field); Annotation annotation = null; String defaultValue = null; boolean encoded = false; final boolean isProvider = declaringClass.getAnnotation(Provider.class) != null; final List<String> allowedAnnotation = isProvider ? PROVIDER_FIELDS_ANNOTATIONS : RESOURCE_FIELDS_ANNOTATIONS; for (int i = 0, length = annotations.length; i < length; i++) { Class<?> annotationType = annotations[i].annotationType(); if (allowedAnnotation.contains(annotationType.getName())) { if (annotation != null) { throw new RuntimeException( String.format("JAX-RS annotations on one of fields %s are equivocality. Annotations: %s and %s can't be applied to one field. ", field, annotation, annotations[i])); } annotation = annotations[i]; } else if (annotationType == Encoded.class && !isProvider) { encoded = true; } else if (annotationType == DefaultValue.class && !isProvider) { defaultValue = ((DefaultValue)annotations[i]).value(); } } this.defaultValue = defaultValue; this.annotation = annotation; this.encoded = encoded || declaringClass.getAnnotation(Encoded.class) != null; }
Example 12
Source Project: usergrid File: Controller.java License: Apache License 2.0 | 5 votes |
/** * Scans all @IterationChop and @TimeChop annotated test classes in code base * and sets @ChopCluster annotated fields in these classes to their runtime values. * <p> * For this to work properly, fields in test classes should be declared as follows: * <p> * <code>@ChopCluster( name = "ClusterName" )</code> * <code>public static ICoordinatedCluster clusterToBeInjected;</code> * </p> * In this case, <code>clusterToBeInjected</code> field will be set to the cluster object * taken from the coordinator, if indeed a cluster with a name of "ClusterName" exists. */ private void injectClusters() { Collection<Class<?>> testClasses = new LinkedList<Class<?>>(); testClasses.addAll( iterationChopClasses ); testClasses.addAll( timeChopClasses ); for( Class<?> iterationTest : testClasses ) { LOG.info( "Scanning test class {} for annotations", iterationTest.getName() ); for( Field f : iterationTest.getDeclaredFields() ) { if( f.getType().isAssignableFrom( ICoordinatedCluster.class ) ) { for( Annotation annotation : f.getDeclaredAnnotations() ) { if( annotation.annotationType().equals( ChopCluster.class ) ) { String clusterName = ( ( ChopCluster ) annotation).name(); ICoordinatedCluster cluster; if ( ! clusterMap.containsKey( clusterName ) || ( cluster = clusterMap.get( clusterName ) ) == null ) { LOG.warn( "No clusters found with name: {}", clusterName ); continue; } try { LOG.info( "Setting cluster {} on {} field", clusterName, f.getName() ); f.set( null, cluster ); } catch ( IllegalAccessException e ) { LOG.error( "Cannot access field {}", f.getName(), e ); } } } } } } }
Example 13
Source Project: cxf File: InjectionUtilsTest.java License: Apache License 2.0 | 5 votes |
@Test(expected = InternalServerErrorException.class) public void testJsr310DateExceptionHandling() { Field field = CustomerDetailsWithAdapter.class.getDeclaredFields()[0]; Annotation[] paramAnns = field.getDeclaredAnnotations(); InjectionUtils.createParameterObject(Collections.singletonList("wrongDate"), LocalDate.class, LocalDate.class, paramAnns, null, false, ParameterType.QUERY, createMessage()); }
Example 14
Source Project: beam File: ApiSurface.java License: Apache License 2.0 | 5 votes |
private void addExposedTypes(Field field, Class<?> cause) { addExposedTypes(field.getGenericType(), cause); for (Annotation annotation : field.getDeclaredAnnotations()) { LOG.debug( "Adding exposed types from {}, which is an annotation on field {}", annotation, field); addExposedTypes(annotation.annotationType(), cause); } }
Example 15
Source Project: Java-Coding-Problems File: Main.java License: MIT License | 4 votes |
public static void main(String[] args) throws ReflectiveOperationException { Class<Melon> clazz = Melon.class; System.out.println("Inspecting package annotations: "); Annotation[] pckgAnnotations = clazz.getPackage().getAnnotations(); System.out.println("Package annotations: " + Arrays.toString(pckgAnnotations)); System.out.println("\nInspecting class annotations: "); Annotation[] clazzAnnotations = clazz.getAnnotations(); System.out.println("Class annotations: " + Arrays.toString(clazzAnnotations)); Fruit fruitAnnotation = (Fruit) clazzAnnotations[0]; System.out.println("@Fruit name: " + fruitAnnotation.name()); System.out.println("@Fruit value: " + fruitAnnotation.value()); System.out.println("\nInspecting methods annotations: "); Method methodEat = clazz.getDeclaredMethod("eat"); Annotation[] methodAnnotations = methodEat.getDeclaredAnnotations(); System.out.println("Method annotations: " + Arrays.toString(methodAnnotations)); Ripe ripeAnnotation = (Ripe) methodAnnotations[0]; System.out.println("@Ripe value: " + ripeAnnotation.value()); System.out.println("\nInspecting annotations of the thrown exceptions: "); AnnotatedType[] exceptionsTypes = methodEat.getAnnotatedExceptionTypes(); System.out.println("Exceptions types: " + Arrays.toString(exceptionsTypes)); System.out.println("First exception type: " + exceptionsTypes[0].getType()); System.out.println("Annotations of the first exception type: " + Arrays.toString(exceptionsTypes[0].getAnnotations())); System.out.println("\nInspecting annotations of the return type"); Method methodSeeds = clazz.getDeclaredMethod("seeds"); AnnotatedType returnType = methodSeeds.getAnnotatedReturnType(); System.out.println("Return type: " + returnType.getType().getTypeName()); System.out.println("Annotations of the return type: " + Arrays.toString(returnType.getAnnotations())); System.out.println("\nInspecting annotations of the method's parameters: "); Method methodSlice = clazz.getDeclaredMethod("slice", int.class); Annotation[][] paramAnnotations = methodSlice.getParameterAnnotations(); Class<?>[] parameterTypes = methodSlice.getParameterTypes(); int i = 0; for (Annotation[] annotations : paramAnnotations) { Class parameterType = parameterTypes[i++]; System.out.println("Parameter type: " + parameterType.getName()); for (Annotation annotation : annotations) { System.out.println("Annotation: " + annotation); System.out.println("Annotation name: " + annotation.annotationType().getSimpleName()); } } System.out.println("\nInspecting annotations of fields: "); Field weightField = clazz.getDeclaredField("weight"); Annotation[] fieldAnnotations = weightField.getDeclaredAnnotations(); Unit unitFieldAnnotation = (Unit) fieldAnnotations[0]; System.out.println("@Unit value: " + unitFieldAnnotation.value()); System.out.println("\nInspecting annotations of superclass: "); AnnotatedType superclassType = clazz.getAnnotatedSuperclass(); System.out.println("Superclass type: " + superclassType.getType().getTypeName()); System.out.println("Annotations: " + Arrays.toString(superclassType.getDeclaredAnnotations())); System.out.println("@Family annotation present: " + superclassType.isAnnotationPresent(Family.class)); System.out.println("\nInspecting annotations of interfaces: "); AnnotatedType[] interfacesTypes = clazz.getAnnotatedInterfaces(); System.out.println("Interfaces types: " + Arrays.toString(interfacesTypes)); System.out.println("First interface type: " + interfacesTypes[0].getType()); System.out.println("Annotations of the first exception type: " + Arrays.toString(interfacesTypes[0].getAnnotations())); System.out.println("\nGet annotations by type:"); Fruit[] clazzFruitAnnotations = clazz.getAnnotationsByType(Fruit.class); for (Fruit clazzFruitAnnotation : clazzFruitAnnotations) { System.out.println("Fruit annotation name: " + clazzFruitAnnotation.name()); System.out.println("Fruit annotation value: " + clazzFruitAnnotation.value()); } System.out.println("\nGet a declared annotation:"); Ripe methodRipeAnnotation = methodEat.getDeclaredAnnotation(Ripe.class); System.out.println("Shape annotation value: " + methodRipeAnnotation.value()); }
Example 16
Source Project: joyqueue File: Validators.java License: Apache License 2.0 | 4 votes |
/** * 绑定上下文 * * @param target 对象 * @throws ReflectException */ public static void validate(final Object target) throws ValidateException { if (target == null) { return; } Class<?> clazz = target.getClass(); Field[] fields; Annotation[] annotations; Validator validator; Getter getter; // 遍历类及其父类 while (clazz != null && clazz != Object.class) { // 获取字段 fields = clazz.getDeclaredFields(); // 遍历字段 for (Field field : fields) { // 可能存在多个验证声明,只需要获取一次值 getter = null; // 获取声明 annotations = field.getDeclaredAnnotations(); if (annotations != null) { // 遍历声明 for (Annotation annotation : annotations) { validator = getValidator(annotation); // 判断是否能验证 if (validator != null) { // 获取该字段的值 if (getter == null) { getter = Getters.field(field, target, true); } // 验证 try { validator.validate(target, annotation, new Validator.Value(field.getName(), field.getType(), getter.get())); } catch (ReflectException e) { throw new ValidateException(e.getMessage(), e); } } } } } // 父类 clazz = clazz.getSuperclass(); } }
Example 17
Source Project: framework File: OModel.java License: GNU Affero General Public License v3.0 | 4 votes |
private boolean compatibleField(Field field) { if (mOdooVersion != null) { Annotation[] annotations = field.getDeclaredAnnotations(); if (annotations.length > 0) { int version = 0; for (Annotation annotation : annotations) { // Check for odoo api annotation Class<? extends Annotation> type = annotation.annotationType(); if (type.getDeclaringClass().isAssignableFrom(Odoo.api.class)) { switch (mOdooVersion.getVersionNumber()) { case 11: if (type.isAssignableFrom(Odoo.api.v11alpha.class)) { version++; } break; case 10: if (type.isAssignableFrom(Odoo.api.v10.class)) { version++; } break; case 9: if (type.isAssignableFrom(Odoo.api.v9.class)) { version++; } break; case 8: if (type.isAssignableFrom(Odoo.api.v8.class)) { version++; } break; case 7: if (type.isAssignableFrom(Odoo.api.v7.class)) { version++; } break; } } // Check for functional annotation if (type.isAssignableFrom(Odoo.Functional.class) || type.isAssignableFrom(Odoo.onChange.class) || type.isAssignableFrom(Odoo.Domain.class) || type.isAssignableFrom(Odoo.SyncColumnName.class)) { version++; } } return (version > 0); } return true; } return false; }
Example 18
Source Project: mybatis.flying File: SqlBuilder.java License: Apache License 2.0 | 4 votes |
/** * The class of the incoming dto object builds the QueryMapper object, and the * constructed object is stored in the cache, which is retrieved directly from * the cache later. * * @param dtoClass * @param pojoClass * @return QueryMapper */ private static QueryMapper buildQueryMapper(Class<?> dtoClass, Class<?> pojoClass) { QueryMapper queryMapper = queryMapperCache.get(dtoClass); if (queryMapper != null) { return queryMapper; } Map<String, ConditionMapper> conditionMapperCache = new WeakHashMap<>(16); Map<String, OrMapper> orMapperCache = new WeakHashMap<>(4); Field[] fields = null; ConditionMapperAnnotation conditionMapperAnnotation = null; ConditionMapper conditionMapper = null; Or or = null; OrMapper orMapper = null; queryMapper = new QueryMapper(); fields = dtoClass.getDeclaredFields(); Annotation[] conditionAnnotations = null; for (Field field : fields) { conditionAnnotations = field.getDeclaredAnnotations(); if (conditionAnnotations.length == 0) { continue; } for (Annotation an : conditionAnnotations) { if (an instanceof ConditionMapperAnnotation) { conditionMapperAnnotation = (ConditionMapperAnnotation) an; conditionMapper = new ConditionMapper(); buildConditionMapper(conditionMapper, conditionMapperAnnotation, pojoClass, field); conditionMapperCache.put(field.getName(), conditionMapper); } else if (an instanceof Or) { or = (Or) an; orMapper = new OrMapper(); orMapper.setFieldName(field.getName()); ConditionMapper[] conditionMappers = new ConditionMapper[or.value().length]; int i = 0; for (ConditionMapperAnnotation cma : or.value()) { conditionMappers[i] = new ConditionMapper(); buildConditionMapper(conditionMappers[i], cma, pojoClass, field); i++; } orMapper.setConditionMappers(conditionMappers); orMapperCache.put(field.getName(), orMapper); } } } queryMapper.setConditionMapperCache(conditionMapperCache); queryMapper.setOrMapperCache(orMapperCache); queryMapperCache.put(dtoClass, queryMapper); return queryMapper; }
Example 19
Source Project: cxf File: JAXBUtilsTest.java License: Apache License 2.0 | 4 votes |
private void correctValueType(Class<?> clazz) { Field field = clazz.getDeclaredFields()[0]; Annotation[] paramAnns = field.getDeclaredAnnotations(); Class<?> valueType = JAXBUtils.getValueTypeFromAdapter(LocalDate.class, LocalDate.class, paramAnns); Assert.assertEquals(String.class, valueType); }
Example 20
Source Project: simplexml File: FieldDetail.java License: Apache License 2.0 | 2 votes |
/** * Constructor for the <code>FieldDetail</code> object. This takes * a field that has been extracted from a class. All of the details * such as the annotations and the field name are stored. * * @param field this is the field that is represented by this */ public FieldDetail(Field field) { this.list = field.getDeclaredAnnotations(); this.name = field.getName(); this.field = field; }