List of usage examples for java.lang Class getDeclaredFields
@CallerSensitive public Field[] getDeclaredFields() throws SecurityException
From source file:Main.java
/** * Gets the given class's {@link Field}s marked with the annotation of the * specified class.// w w w . j av a2s . c o m * <p> * Unlike {@link Class#getFields()}, the result will include any non-public * fields, including fields defined in supertypes of the given class. * </p> * * @param c The class to scan for annotated fields. * @param annotationClass The type of annotation for which to scan. * @param fields The list to which matching fields will be added. */ public static <A extends Annotation> void getAnnotatedFields(final Class<?> c, final Class<A> annotationClass, final List<Field> fields) { if (c == null) return; // check supertypes for annotated fields first getAnnotatedFields(c.getSuperclass(), annotationClass, fields); for (final Class<?> iface : c.getInterfaces()) { getAnnotatedFields(iface, annotationClass, fields); } for (final Field f : c.getDeclaredFields()) { final A ann = f.getAnnotation(annotationClass); if (ann != null) fields.add(f); } }
From source file:Main.java
public static List<Field> getAccessibleFields(Class<?> clazz, Class<?> limit) { Package topPackage = clazz.getPackage(); List<Field> fieldList = new ArrayList<Field>(); int topPackageHash = topPackage == null ? 0 : topPackage.hashCode(); boolean top = true; do {/* w w w .j a v a2 s . c om*/ if (clazz == null) { break; } Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { if (top == true) { // add all top declared fields fieldList.add(field); continue; } int modifier = field.getModifiers(); if (Modifier.isPrivate(modifier) == true) { continue; // ignore super private fields } if (Modifier.isPublic(modifier) == true) { addFieldIfNotExist(fieldList, field); // add super public methods continue; } if (Modifier.isProtected(modifier) == true) { addFieldIfNotExist(fieldList, field); // add super protected methods continue; } // add super default methods from the same package Package pckg = field.getDeclaringClass().getPackage(); int pckgHash = pckg == null ? 0 : pckg.hashCode(); if (pckgHash == topPackageHash) { addFieldIfNotExist(fieldList, field); } } top = false; } while ((clazz = clazz.getSuperclass()) != limit); return fieldList; }
From source file:edu.brown.utils.ClassUtil.java
/** * @param clazz//from w w w .ja va 2 s. c o m * @return */ public static <T> Field[] getFieldsByType(Class<?> clazz, Class<? extends T> fieldType) { List<Field> fields = new ArrayList<Field>(); for (Field f : clazz.getDeclaredFields()) { int modifiers = f.getModifiers(); if (Modifier.isTransient(modifiers) == false && Modifier.isPublic(modifiers) == true && Modifier.isStatic(modifiers) == false && ClassUtil.getSuperClasses(f.getType()).contains(fieldType)) { fields.add(f); } } // FOR return (fields.toArray(new Field[fields.size()])); }
From source file:io.github.benas.randombeans.util.ReflectionUtils.java
/** * Get inherited fields of a given type. * * @param type the type to introspect//from w w w. j a va 2 s .co m * @return list of inherited fields */ public static List<Field> getInheritedFields(Class<?> type) { List<Field> inheritedFields = new ArrayList<>(); while (type.getSuperclass() != null) { Class<?> superclass = type.getSuperclass(); inheritedFields.addAll(asList(superclass.getDeclaredFields())); type = superclass; } return inheritedFields; }
From source file:edu.usu.sdl.openstorefront.doc.EntityProcessor.java
private static void addFields(Class entity, EntityDocModel docModel) { if (entity != null) { Field[] fields = entity.getDeclaredFields(); for (Field field : fields) { //Skip static field if ((Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) == false) { EntityFieldModel fieldModel = new EntityFieldModel(); fieldModel.setName(field.getName()); fieldModel.setType(field.getType().getSimpleName()); fieldModel.setOriginClass(entity.getSimpleName()); fieldModel.setEmbeddedType(ReflectionUtil.isComplexClass(field.getType())); if (ReflectionUtil.isCollectionClass(field.getType())) { DataType dataType = (DataType) field.getAnnotation(DataType.class); if (dataType != null) { String typeClass = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeClass = dataType.actualClassName(); }// w ww .jav a 2 s.co m fieldModel.setGenericType(typeClass); } } APIDescription description = (APIDescription) field.getAnnotation(APIDescription.class); if (description != null) { fieldModel.setDescription(description.value()); } for (Annotation annotation : field.getAnnotations()) { if (annotation.annotationType().getName().equals(APIDescription.class.getName()) == false) { EntityConstraintModel entityConstraintModel = new EntityConstraintModel(); entityConstraintModel.setName(annotation.annotationType().getSimpleName()); APIDescription annotationDescription = (APIDescription) annotation.annotationType() .getAnnotation(APIDescription.class); if (annotationDescription != null) { entityConstraintModel.setDescription(annotationDescription.value()); } //rules Object annObj = field.getAnnotation(annotation.annotationType()); if (annObj instanceof NotNull) { entityConstraintModel.setRules("Field is required"); } else if (annObj instanceof PK) { PK pk = (PK) annObj; entityConstraintModel.setRules("<b>Generated:</b> " + pk.generated()); fieldModel.setPrimaryKey(true); } else if (annObj instanceof FK) { FK fk = (FK) annObj; StringBuilder sb = new StringBuilder(); sb.append("<b>Foreign Key:</b> ").append(fk.value().getSimpleName()); sb.append(" (<b>Enforce</b>: ").append(fk.enforce()); sb.append(" <b>Soft reference</b>: ").append(fk.softReference()); if (StringUtils.isNotBlank(fk.referencedField())) { sb.append(" <b>Reference Field</b>: ").append(fk.referencedField()); } sb.append(" )"); entityConstraintModel.setRules(sb.toString()); } else if (annObj instanceof ConsumeField) { entityConstraintModel.setRules(""); } else if (annObj instanceof Size) { Size size = (Size) annObj; entityConstraintModel .setRules("<b>Min:</b> " + size.min() + " <b>Max:</b> " + size.max()); } else if (annObj instanceof Pattern) { Pattern pattern = (Pattern) annObj; entityConstraintModel.setRules("<b>Pattern:</b> " + pattern.regexp()); } else if (annObj instanceof Sanitize) { Sanitize sanitize = (Sanitize) annObj; entityConstraintModel .setRules("<b>Sanitize:</b> " + sanitize.value().getSimpleName()); } else if (annObj instanceof Unique) { Unique unique = (Unique) annObj; entityConstraintModel.setRules("<b>Handler:</b> " + unique.value().getSimpleName()); } else if (annObj instanceof ValidValueType) { ValidValueType validValueType = (ValidValueType) annObj; StringBuilder sb = new StringBuilder(); if (validValueType.value().length > 0) { sb.append(" <b>Values:</b> ").append(Arrays.toString(validValueType.value())); } if (validValueType.lookupClass().length > 0) { sb.append(" <b>Lookups:</b> "); for (Class lookupClass : validValueType.lookupClass()) { sb.append(lookupClass.getSimpleName()).append(" "); } } if (validValueType.enumClass().length > 0) { sb.append(" <b>Enumerations:</b> "); for (Class enumClass : validValueType.enumClass()) { sb.append(enumClass.getSimpleName()).append(" ("); sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")"); } } entityConstraintModel.setRules(sb.toString()); } else if (annObj instanceof Min) { Min min = (Min) annObj; entityConstraintModel.setRules("<b>Min value:</b> " + min.value()); } else if (annObj instanceof Max) { Max max = (Max) annObj; entityConstraintModel.setRules("<b>Max value:</b> " + max.value()); } else if (annObj instanceof Version) { entityConstraintModel.setRules("Entity version; For Multi-Version control"); } else if (annObj instanceof DataType) { DataType dataType = (DataType) annObj; String typeClass = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeClass = dataType.actualClassName(); } entityConstraintModel.setRules("<b>Type:</b> " + typeClass); } else { entityConstraintModel.setRules(annotation.toString()); } //Annotations that have related classes if (annObj instanceof DataType) { DataType dataType = (DataType) annObj; entityConstraintModel.getRelatedClasses().add(dataType.value().getSimpleName()); } if (annObj instanceof FK) { FK fk = (FK) annObj; entityConstraintModel.getRelatedClasses().add(fk.value().getSimpleName()); } if (annObj instanceof ValidValueType) { ValidValueType validValueType = (ValidValueType) annObj; for (Class lookupClass : validValueType.lookupClass()) { entityConstraintModel.getRelatedClasses().add(lookupClass.getSimpleName()); } StringBuilder sb = new StringBuilder(); for (Class enumClass : validValueType.enumClass()) { sb.append("<br>"); sb.append(enumClass.getSimpleName()).append(": ("); sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")"); } entityConstraintModel .setRules(entityConstraintModel.getRules() + " " + sb.toString()); } fieldModel.getConstraints().add(entityConstraintModel); } } docModel.getFieldModels().add(fieldModel); } } addFields(entity.getSuperclass(), docModel); } }
From source file:ObjectInspector.java
/** * Recurses up the inheritance chain and collects all the fields * /* ww w. j a v a 2 s. c o m*/ * @param fields * The collection of fields found so far * @param c * The class to get fields from */ private static void getFields(Collection<Field> fields, Class c) { for (Field f : c.getDeclaredFields()) { fields.add(f); } if (c.getSuperclass() != null) { getFields(fields, c.getSuperclass()); } }
From source file:org.oncoblocks.centromere.web.controller.RequestUtils.java
/** * Checks a request parameter name against all possible {@link Model} attributes, converting it to * the appropriate repository field name for querying and sorting. * * @param param// w ww .ja v a2s . co m * @return */ public static String remapParameterName(String param, Class<? extends Model<?>> model) { logger.debug(String.format("Attempting to remap query string parameter: %s", param)); for (Field field : model.getDeclaredFields()) { String fieldName = field.getName(); if (field.isAnnotationPresent(Aliases.class)) { Aliases aliases = field.getAnnotation(Aliases.class); for (Alias alias : aliases.value()) { if (alias.value().equals(param)) return fieldName; } } else if (field.isAnnotationPresent(Alias.class)) { Alias alias = field.getAnnotation(Alias.class); if (alias.value().equals(param)) return fieldName; } } logger.debug(String.format("Parameter remapped to: %s", param)); return param; }
From source file:com.palantir.ptoss.util.Reflections.java
/** * Returns the list of fields on this class annotated with the passed {@link Annotation} * @param klass checks the {@link Field}s on this class * @param annotation looks for this {@link Annotation} * @return list of all {@link Field}s that are annotated with the specified {@link Annotation} *///from w w w.java 2 s . co m public static List<Field> getAnnotatedFields(Class<?> klass, Class<? extends Annotation> annotation) { List<Field> annotatedFields = Lists.newArrayList(); for (Field f : klass.getDeclaredFields()) { if (f.isAnnotationPresent(annotation)) { annotatedFields.add(f); } } return annotatedFields; }
From source file:com.github.gekoh.yagen.util.FieldInfo.java
public static AccessibleObject getIdFieldOrMethod(Class entityClass) { for (Field field : entityClass.getDeclaredFields()) { if (field.isAnnotationPresent(Id.class)) { return field; }/*from ww w.j ava 2 s. c o m*/ } for (Method method : entityClass.getDeclaredMethods()) { if (method.isAnnotationPresent(Id.class)) { return method; } } return entityClass.getSuperclass() != null ? getIdFieldOrMethod(entityClass.getSuperclass()) : null; }
From source file:com.htmlhifive.pitalium.core.config.PtlTestConfig.java
/** * {@link PtlConfigurationProperty}????????? * //from w w w . java 2 s . c om * @param object ? * @param arguments ? */ private static void fillConfigProperties(Object object, Map<String, String> arguments) { // Collect all fields include super classes Class clss = object.getClass(); List<Field> fields = new ArrayList<Field>(); Collections.addAll(fields, clss.getDeclaredFields()); while ((clss = clss.getSuperclass()) != Object.class) { Collections.addAll(fields, clss.getDeclaredFields()); } for (Field field : fields) { PtlConfigurationProperty propertyConfig = field.getAnnotation(PtlConfigurationProperty.class); if (propertyConfig == null) { PtlConfiguration config = field.getAnnotation(PtlConfiguration.class); if (config == null) { continue; } // Field is nested config class try { field.setAccessible(true); Object prop = field.get(object); if (prop != null) { fillConfigProperties(prop, arguments); } } catch (TestRuntimeException e) { throw e; } catch (Exception e) { throw new TestRuntimeException(e); } continue; } String value = arguments.get(propertyConfig.value()); if (value == null) { continue; } try { Object applyValue = convertFromString(field.getType(), value); field.setAccessible(true); field.set(object, applyValue); LOG.trace("[Load config] override property ({}). [{} => {}]", clss.getSimpleName(), field.getName(), applyValue); } catch (TestRuntimeException e) { throw e; } catch (Exception e) { throw new TestRuntimeException("ConfigurationProperty convert error", e); } } }