Java Code Examples for org.apache.commons.lang3.reflect.FieldUtils#getAllFields()

The following examples show how to use org.apache.commons.lang3.reflect.FieldUtils#getAllFields() . 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: BeanConvertUtil.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
private static void objectFieldsPutMap(Object dstBean, BeanMap beanMap, Map orgMap) {
    //Field[] fields = dstBean.getClass().getDeclaredFields();
    Field[] fields = FieldUtils.getAllFields(dstBean.getClass());
    for (Field field : fields) {
        if (!orgMap.containsKey(field.getName())) {
            continue;
        }
        Class dstClass = field.getType();
        //System.out.println("字段类型" + dstClass);

        Object value = orgMap.get(field.getName());
        //String 转date
        Object tmpValue = Java110Converter.getValue(value, dstClass);
        beanMap.put(field.getName(), tmpValue);
    }
}
 
Example 2
Source File: ConnectionConf.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Clears all fields that match a particular predicate. For all primitive types, the value is set
 * to zero. For object types, the value is set to null.
 *
 * @param predicate
 */
private void clear(Predicate<Field> predicate, boolean isSecret) {
  try {
    for(Field field : FieldUtils.getAllFields(getClass())) {
      if(predicate.apply(field)) {
        if (isSecret && field.getType().equals(String.class)) {
          final String value = (String) field.get(this);

          if (Strings.isNullOrEmpty(value)) {
            field.set(this, null);
          } else {
            field.set(this, USE_EXISTING_SECRET_VALUE);
          }
        } else {
          Object defaultValue = Defaults.defaultValue(field.getType());
          field.set(this, defaultValue);
        }
      }
    }
  } catch (IllegalAccessException e) {
    throw Throwables.propagate(e);
  }
}
 
Example 3
Source File: ConnectionConf.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Applies secret values from existingConf to the connectionConf if they are set to {@link USE_EXISTING_SECRET_VALUE}.
 *
 * @param existingConf
 */
public void applySecretsFrom(ConnectionConf existingConf) {
  for (Field field : FieldUtils.getAllFields(getClass())) {
    if (field.getAnnotation(Secret.class) == null) {
      continue;
    }

    try {
      if (field.getType().equals(String.class) && USE_EXISTING_SECRET_VALUE.equals(field.get(this))) {
        field.set(this, field.get(existingConf));
      }
    } catch (IllegalAccessException e) {
      throw Throwables.propagate(e);
    }
  }
}
 
Example 4
Source File: CommonCsvExportAggregator.java    From allure2 with Apache License 2.0 6 votes vote down vote up
@Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {

    super.setColumnMapping(new String[FieldUtils.getAllFields(bean.getClass()).length]);
    final int numColumns = findMaxFieldIndex();
    if (!isAnnotationDriven() || numColumns == -1) {
        return super.generateHeader(bean);
    }

    String[] header = new String[numColumns + 1];

    BeanField<T> beanField;
    for (int i = 0; i <= numColumns; i++) {
        beanField = findField(i);
        String columnHeaderName = extractHeaderName(beanField);
        header[i] = columnHeaderName;
    }
    return header;
}
 
Example 5
Source File: CacheStatisticsControllerEnricher.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void enrich(Object testCase) {
    Validate.notNull(registry.get(), "registry should not be null");
    Validate.notNull(jmxConnectorRegistry.get(), "jmxConnectorRegistry should not be null");
    Validate.notNull(suiteContext.get(), "suiteContext should not be null");

    for (Field field : FieldUtils.getAllFields(testCase.getClass())) {
        JmxInfinispanCacheStatistics annotation = field.getAnnotation(JmxInfinispanCacheStatistics.class);

        if (annotation == null) {
            continue;
        }

        try {
            FieldUtils.writeField(field, testCase, getInfinispanCacheStatistics(annotation), true);
        } catch (IOException | IllegalAccessException | MalformedObjectNameException e) {
            throw new RuntimeException("Could not set value on field " + field);
        }
    }
}
 
Example 6
Source File: PropertyObject.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public void copyTo(Object o, boolean ignoreNull, Collection<String> excludes) throws Exception {
	for (Field fld : FieldUtils.getAllFields(this.getClass())) {
		if (!excludes.contains(fld.getName())) {
			if (PropertyUtils.isReadable(this, fld.getName()) && PropertyUtils.isWriteable(o, fld.getName())) {
				Object value = PropertyUtils.getProperty(this, fld.getName());
				if (ignoreNull && (null == value)) {
					continue;
				}
				PropertyUtils.setProperty(o, fld.getName(), value);
			}
		}
	}
}
 
Example 7
Source File: WrapCopierFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static List<String> getAllFieldNames(Class<?> cls) throws Exception {
	List<String> names = new ArrayList<>();
	for (Field field : FieldUtils.getAllFields(cls)) {
		names.add(field.getName());
	}
	return names;
}
 
Example 8
Source File: EntityManagerContainer.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T extends JpaObject, W extends GsonPropertyObject> T fetch(String id, Class<T> clz, Class<W> wrapClass)
		throws Exception {
	List<String> list = new ArrayList<>();
	for (Field field : FieldUtils.getAllFields(wrapClass)) {
		Field jpaField = FieldUtils.getField(clz, field.getName(), true);
		if ((null != jpaField) && (!Collection.class.isAssignableFrom(jpaField.getType()))) {
			list.add(field.getName());
		}
	}
	return this.fetch(id, clz, list);
}
 
Example 9
Source File: EntityManagerContainer.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T extends JpaObject, W extends GsonPropertyObject> List<T> fetch(Collection<String> ids, Class<T> clz,
		Class<W> wrapClass) throws Exception {
	List<String> list = new ArrayList<>();
	for (Field field : FieldUtils.getAllFields(wrapClass)) {
		Field jpaField = FieldUtils.getField(clz, field.getName(), true);
		if ((null != jpaField) && (!Collection.class.isAssignableFrom(jpaField.getType()))) {
			list.add(field.getName());
		}
	}
	return this.fetch(ids, clz, list);
}
 
Example 10
Source File: DataChangeListenerTestBase.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
static final void setFinalStatic(final Class<?> cls, final String fieldName, final Object newValue)
        throws SecurityException, ReflectiveOperationException {
    Field[] fields = FieldUtils.getAllFields(cls);
    for (Field field : fields) {
        if (fieldName.equals(field.getName())) {
            field.setAccessible(true);
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
            field.set(null, newValue);
            break;
        }
    }
}
 
Example 11
Source File: UifServletRequestDataBinder.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Determines the root property paths relative to the given root object type against which to perform automatic
 * linking.
 *
 * <p>This will be determined based on the presence of {@link Link} annotations on the given root object type.
 * This method is invoked recursively as it walks the class structure looking for Link annotations. It uses the
 * path
 * and scanned arguments to keep track of how deep into the structure the scanning is and to prevent infinite
 * recursion.</p>
 *
 * @param rootObjectType the root object type from which to perform the scan for auto-linking paths
 * @param path the current property path relative to the original root object type at which the scan began, if null
 * then we are scanning from the root-most object type. Each recursive call of this method will append
 * a new property to this path
 * @param scanned used to track classes that have already been scanned and prevent infinite recursion
 * @return a set of property paths that should be auto linked
 */
protected Set<String> determineRootAutoLinkingPaths(Class<?> rootObjectType, String path, Set<Class<?>> scanned) {
    Set<String> autoLinkingPaths = new HashSet<String>();
    if (scanned.contains(rootObjectType)) {
        return autoLinkingPaths;
    } else {
        scanned.add(rootObjectType);
    }
    Link autoLink = AnnotationUtils.findAnnotation(rootObjectType, Link.class);
    if (autoLink != null && autoLink.cascade()) {
        autoLinkingPaths.addAll(assembleAutoLinkingPaths(path, autoLink));
    } else if (autoLink == null) {
        Field[] fields = FieldUtils.getAllFields(rootObjectType);
        for (Field field : fields) {
            autoLink = field.getAnnotation(Link.class);
            if (autoLink != null) {
                if (autoLink.cascade()) {
                    String fieldPath = appendToPath(path, field.getName());
                    autoLinkingPaths.addAll(assembleAutoLinkingPaths(fieldPath, autoLink));
                }
            } else {
                autoLinkingPaths.addAll(determineRootAutoLinkingPaths(field.getType(), appendToPath(path,
                        field.getName()), scanned));
            }
        }
    }
    return autoLinkingPaths;
}
 
Example 12
Source File: ReferenceLinker.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
* Gets indexes that have been modified.
*
* <p>
*     Returns a list of cascade links in the field names that are also in the decomposed paths.
* </p>
*
* @param decomposedPaths contains field names to be used.
* @param linked
* @param wrapped used to get all field names.
*/
protected void cascadeLinkingAnnotations(DataObjectWrapper<?> wrapped, Map<String, Set<String>> decomposedPaths,
        Set<Object> linked) {
    Field[] fields = FieldUtils.getAllFields(wrapped.getWrappedClass());
    Map<String, Field> modifiedFieldMap = new HashMap<String, Field>();
    for (Field field : fields) {
        if (decomposedPaths.containsKey(field.getName())) {
            modifiedFieldMap.put(field.getName(), field);
        }
    }
    for (String modifiedFieldName : modifiedFieldMap.keySet()) {
        Field modifiedField = modifiedFieldMap.get(modifiedFieldName);
        Link link = modifiedField.getAnnotation(Link.class);
        if (link == null) {
            // check if they have an @Link on the class itself
            link = AnnotationUtils.findAnnotation(modifiedField.getType(), Link.class);
        }
        if (link != null && link.cascade()) {
            List<String> linkingPaths = assembleLinkingPaths(link);
            for (String linkingPath : linkingPaths) {
                Map<String, Set<String>> decomposedLinkingPath =
                        decomposePropertyPaths(decomposedPaths.get(modifiedFieldName), linkingPath);
                String valuePath = modifiedFieldName;
                if (StringUtils.isNotBlank(linkingPath)) {
                    valuePath = valuePath + "." + link.path();
                }
                Object linkRootObject = wrapped.getPropertyValueNullSafe(valuePath);
                linkChangesInternal(linkRootObject, decomposedLinkingPath, linked);
            }
        }
    }
}