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

The following examples show how to use org.apache.commons.lang3.reflect.FieldUtils#getField() . 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: PostgisGeoPlugin.java    From dolphin with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validate(List<String> warnings) {
	boolean valid = true;
	srid = properties.getProperty(SRID_NAME);
	if(StringUtils.isEmpty(srid)){
		srid = "3857";
	}
	if(connection == null){
        try {
			connection = ConnectionFactory.getInstance().getConnection(context.getJdbcConnectionConfiguration());
		} catch (SQLException e) {
			e.printStackTrace();
			valid = false;
		}	
	}
	elementsList = FieldUtils.getField(XmlElement.class, "elements", true);
	return valid;
}
 
Example 2
Source File: CheckCore.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void checkIdCreateTimeUpdateTimeSequenceIndex(List<Class<?>> classes) throws Exception {
	for (Class<?> cls : classes) {
		Field idField = FieldUtils.getField(cls, JpaObject.id_FIELDNAME, true);
		Field createTimeField = FieldUtils.getField(cls, JpaObject.createTime_FIELDNAME, true);
		Field updateTimeField = FieldUtils.getField(cls, JpaObject.updateTime_FIELDNAME, true);
		Field sequenceField = FieldUtils.getField(cls, JpaObject.sequence_FIELDNAME, true);
		if ((null != idField.getAnnotation(Index.class)) || (null != createTimeField.getAnnotation(Index.class))
				|| (null != updateTimeField.getAnnotation(Index.class))
				|| (null != sequenceField.getAnnotation(Index.class))) {
			System.err.println(
					String.format("checkIdCreateTimeUpdateTimeSequenceIndex error: class: %s.", cls.getName()));
		}
	}
}
 
Example 3
Source File: ReflectionUtil.java    From glitr with MIT License 5 votes vote down vote up
public static String getDescriptionFromAnnotatedField(Class clazz, Method method) {
    try {
        Field field = FieldUtils.getField(clazz, ReflectionUtil.sanitizeMethodName(method.getName()), true);
        return ReflectionUtil.getDescriptionFromAnnotatedElement(field);
    } catch (Exception e) {
        logger.debug("Could not find a Field associated to the Method [{}]", method.getName());
    }
    return null;
}
 
Example 4
Source File: MDCBuilder.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static String getFieldValue(Object o, String field) {
    try {
        Field privateStringField = FieldUtils.getField(o.getClass(), field, true);
        privateStringField.setAccessible(true);
        return privateStringField.get(o).toString();
    } catch (Exception ignored) {
        return null;
    }
}
 
Example 5
Source File: MtlBaseTaskAction.java    From atlas with Apache License 2.0 5 votes vote down vote up
protected void setFieldValueByReflection(Task task, String fieldName, Object value) {
    Field field = FieldUtils.getField(task.getClass(), fieldName, true);
    if (null == field) {
        throw new StopExecutionException("The field with name:" +
                                                 fieldName +
                                                 " does not existed in class:" +
                                                 task.getClass().getName());
    }
    try {
        FieldUtils.writeField(field, task, value, true);
    } catch (IllegalAccessException e) {
        throw new StopExecutionException(e.getMessage());
    }
}
 
Example 6
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 7
Source File: SecurityDefinition.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Try to fill the name property of some authentication definition, if no user defined value was set.</p>
 * <p>If the current value of the name property is empty, this will fill it to be the same as the name of the
 * security definition.</br>
 * If no {@link Field} named "name" is found inside the given SecuritySchemeDefinition, no action will be taken.
 *
 * @param ssd security scheme
 * @param value value to set the name to
 */
private void tryFillNameField(SecuritySchemeDefinition ssd, String value) {
    if (ssd == null) {
        return;
    }

    Field nameField = FieldUtils.getField(ssd.getClass(), "name", true);
    try {
        if (nameField != null && nameField.get(ssd) == null) {
            nameField.set(ssd, value);
        }
    } catch (IllegalAccessException e) {
        // ignored
    }
}
 
Example 8
Source File: DataRestOperationBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build search operation operation.
 *
 * @param handlerMethod the handler method
 * @param domainType the domain type
 * @param openAPI the open api
 * @param requestMethod the request method
 * @param methodAttributes the method attributes
 * @param methodResourceMapping the method resource mapping
 * @return the operation
 */
private Operation buildSearchOperation(HandlerMethod handlerMethod, Class<?> domainType,
		OpenAPI openAPI, RequestMethod requestMethod, MethodAttributes methodAttributes,
		MethodResourceMapping methodResourceMapping) {
	Operation operation = initOperation(handlerMethod, domainType, requestMethod);
	// Make schema as string if empty
	ParametersMetadata parameterMetadata = methodResourceMapping.getParametersMetadata();
	for (ParameterMetadata parameterMetadatum : parameterMetadata) {
		String pName = parameterMetadatum.getName();
		ResourceDescription description = parameterMetadatum.getDescription();
		if (description instanceof TypedResourceDescription) {
			TypedResourceDescription typedResourceDescription = (TypedResourceDescription) description;
			Field fieldType = FieldUtils.getField(TypedResourceDescription.class, "type", true);
			Class<?> type;
			try {
				type = (Class<?>) fieldType.get(typedResourceDescription);
			}
			catch (IllegalAccessException e) {
				LOGGER.warn(e.getMessage());
				type = String.class;
			}
			Schema<?> schema = SpringDocAnnotationsUtils.resolveSchemaFromType(type, openAPI.getComponents(), null, null);
			Parameter parameter = new Parameter().name(pName).in(ParameterIn.QUERY.toString()).schema(schema);
			operation.addParametersItem(parameter);
		}
	}
	if (methodResourceMapping.isPagingResource()) {
		MethodParameter[] parameters = handlerMethod.getMethodParameters();
		MethodParameter methodParameterPage = Arrays.stream(parameters).filter(methodParameter -> DefaultedPageable.class.equals(methodParameter.getParameterType())).findAny().orElse(null);
		if (methodParameterPage != null) {
			dataRestRequestBuilder.buildCommonParameters(domainType, openAPI, requestMethod, methodAttributes, operation, new String[] { methodParameterPage.getParameterName() }, new MethodParameter[] { methodParameterPage });
		}
	}
	dataRestResponseBuilder.buildSearchResponse(operation, handlerMethod, openAPI, methodResourceMapping, domainType, methodAttributes);
	tagsBuilder.buildSearchTags(operation, openAPI, handlerMethod, domainType);
	return operation;
}
 
Example 9
Source File: DescribeBuilder.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
/** 判断字段是否在Wi中但是没有在Entity类中说明是Wi新增字段,需要进行描述 */
private Boolean inWiNotInEntity(String field, Class<?> clz) {
	try {
		Object o = FieldUtils.readStaticField(clz, "copier", true);
		WrapCopier copier = (WrapCopier) o;
		if ((null != FieldUtils.getField(copier.getOrigClass(), field, true))
				&& (null == FieldUtils.getField(copier.getDestClass(), field, true))) {
			return true;
		}
		return false;
	} catch (Exception e) {
		return null;
	}
}
 
Example 10
Source File: PropertyUtil.java    From minnal with Apache License 2.0 5 votes vote down vote up
public static <T extends Annotation> T getAnnotation(PropertyDescriptor descriptor, Class<T> clazz, boolean ignoreObjectClass) {
	Method method = descriptor.getReadMethod();
	if (method == null || ignoreObjectClass && method.getDeclaringClass().equals(Object.class)) {
		return null;
	}
	
	Field field = FieldUtils.getField(method.getDeclaringClass(), descriptor.getName(), true);
	if (field == null) {
		return null;
	}
	if (field.isAnnotationPresent(clazz)) {
		return field.getAnnotation(clazz);
	}
	return method.getAnnotation(clazz);
}
 
Example 11
Source File: ApiBuilder.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
/** 判断字段是否在Wi中但是没有在Entity类中说明是Wi新增字段,需要进行描述 */
private Boolean inWiNotInEntity(String field, Class<?> clz) {
	try {
		Object o = FieldUtils.readStaticField(clz, "copier", true);
		WrapCopier copier = (WrapCopier) o;
		if ((null != FieldUtils.getField(copier.getOrigClass(), field, true))
				&& (null == FieldUtils.getField(copier.getDestClass(), field, true))) {
			return true;
		}
		return false;
	} catch (Exception e) {
		return null;
	}
}
 
Example 12
Source File: BaseEntityInternalAccess.java    From cuba with Apache License 2.0 5 votes vote down vote up
public static void setValueForHolder(Entity entity, String attribute, @Nullable Object value) {
    Preconditions.checkNotNullArgument(entity, "entity is null");
    Field field = FieldUtils.getField(entity.getClass(), String.format("_persistence_%s_vh",attribute), true);
    if (field == null)
        return;
    try {
        field.set(entity, value);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(String.format("Unable to set value to %s.%s", entity.getClass().getSimpleName(), attribute), e);
    }
}
 
Example 13
Source File: BaseEntityInternalAccess.java    From cuba with Apache License 2.0 5 votes vote down vote up
public static Object getValue(Entity entity, String attribute) {
    Preconditions.checkNotNullArgument(entity, "entity is null");
    Field field = FieldUtils.getField(entity.getClass(), attribute, true);
    if (field == null)
        throw new RuntimeException(String.format("Cannot find field '%s' in class %s", attribute, entity.getClass().getName()));
    try {
        return field.get(entity);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(String.format("Unable to set value to %s.%s", entity.getClass().getSimpleName(), attribute), e);
    }
}
 
Example 14
Source File: STFUGTPPLOG.java    From bartworks with MIT License 5 votes vote down vote up
public static void replaceLogger(){
    try {
        Field loggerField = FieldUtils.getField(Class.forName("gtPlusPlus.api.objects.Logger"), "modLogger", true);
        FieldUtils.removeFinalModifier(loggerField, true);
        loggerField.set(null, new STFUGTPPLOG());
    } catch (IllegalAccessException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example 15
Source File: BW_Util.java    From bartworks with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static List<IRecipe> getGTBufferedRecipeList() throws SecurityException, IllegalArgumentException, IllegalAccessException{
    if (sBufferedRecipeList == null) {
        sBufferedRecipeList = FieldUtils.getDeclaredField(GT_ModHandler.class,"sBufferRecipeList",true);
    }
    if (sBufferedRecipeList == null) {
        sBufferedRecipeList = FieldUtils.getField(GT_ModHandler.class,"sBufferRecipeList",true);
    }
    return (List<IRecipe>) sBufferedRecipeList.get(null);
}
 
Example 16
Source File: CompareUtils.java    From COLA with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static String compareFields(Object target, Object origin, String[] ignoreArr) {

        if(target == null && origin == null){
            return null;
        }
        if(target == null && origin != null ||
        origin == null && target != null){
            return "target is:" + JSON.toJSONString(target) + " .but origin is:" + JSON.toJSONString(origin);
        }

        try{
            List<String> ignoreList = null;
            if(ignoreArr != null && ignoreArr.length > 0){
                // array转化为list
                ignoreList = Arrays.asList(ignoreArr);
            }

            if (target.getClass() == origin.getClass()) {// 只有两个对象都是同一类型的才有可比性

                boolean isTheSame = true;
                if(isBaseType(target)){
                    isTheSame = compareIfBaseField(target, origin);
                    if(!isTheSame){
                        return "compareFields failed, when expect is :" + origin.toString()+ " , and real value is :" + target.toString();
                    }
                }else{
                    Class clazz = target.getClass();
                    //获取object的属性描述
                    PropertyDescriptor[] pds=Introspector.getBeanInfo(clazz,Object.class).getPropertyDescriptors();
                    for(PropertyDescriptor pd:pds){//这里就是所有的属性了
                        String name = pd.getName();//属性名
                        if(ignoreList!= null && ignoreList.contains(name)){
                            continue;
                        }
                        Object o1 = null;
                        Object o2 = null;
                        Method readMethod=pd.getReadMethod();//get方法

                        if(readMethod == null && FieldUtils.getField(clazz, name) == null){
                            continue;
                        }
                        if(readMethod == null){
                            Field f = clazz.getDeclaredField(name);
                            f.setAccessible(true);
                            o1 = f.get(target);
                            o2 = f.get(origin);
                        }else {
                            //在obj1上调用get方法等同于获得obj1的属性值
                            o1 = readMethod.invoke(target);
                            //在obj2上调用get方法等同于获得obj2的属性值
                            o2 = readMethod.invoke(origin);
                        }

                        if(o1 == null && o2 == null){
                            continue;
                        }
                        if(o1 == null && o2 != null){
                            return name + " compareFields failed, when expect is not null , and real value is null,expect value is: " + JSON.toJSONString(o2);
                        }
                        if(o1 != null && o2 == null){
                            return name + " compareFields failed, when expect is  null , and real value is not null, real value is : " +  JSON.toJSONString(o1);
                        }

                        /**
                         * 需要考虑数组,链表等数据结构的对比,看看是否能够复用json解析的功能
                         */
                        /*String subCompareResult =  compareFields(o1, o2, ignoreArr);

                        if(!StringUtils.isEmpty(subCompareResult)){
                            return "compare sub complex Fields failed, subFiled is: " + name + " .inner compare result is:" + subCompareResult;
                        }*/
                        String json1 = JSON.toJSONString(o1);
                        String json2 = JSON.toJSONString(o2);
                        isTheSame = json1.equals(json2);
                        if(!isTheSame){//比较这两个值是否相等,不等就可以放入map了
                            return name + " compareFields failed, when expect is :" + json2+ " , and real value is :" + json1;
                        }
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }

        return null;
    }
 
Example 17
Source File: WrapCopier.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public Boolean fieldNotInOrigInDest(String fieldName) {
	return (null == FieldUtils.getField(origClass, fieldName, true)
			&& (null != FieldUtils.getField(destClass, fieldName, true)));
}
 
Example 18
Source File: JpaObjectTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static <T extends JpaObject> Integer definedLength(Class<T> clz, String attribute) throws Exception {
	Field field = FieldUtils.getField(clz, attribute, true);
	return definedLength(clz, field);
}
 
Example 19
Source File: EntityManagerImpl.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected <T extends Entity> T internalMerge(T entity) {
    try {
        CubaUtil.setSoftDeletion(false);
        CubaUtil.setOriginalSoftDeletion(false);

        UUID uuid = null;
        if (entity.getId() instanceof IdProxy) {
            uuid = ((IdProxy) entity.getId()).getUuid();
        }

        T merged = delegate.merge(entity);

        if (entity.getId() instanceof IdProxy
                && uuid != null
                && !uuid.equals(((IdProxy) merged.getId()).getUuid())) {
            ((IdProxy) merged.getId()).setUuid(uuid);
        }

        // copy non-persistent attributes to the resulting merged instance
        for (MetaProperty property : metadata.getClassNN(entity.getClass()).getProperties()) {
            if (metadata.getTools().isNotPersistent(property) && !property.isReadOnly()) {
                // copy using reflection to avoid executing getter/setter code
                Field field = FieldUtils.getField(entity.getClass(), property.getName(), true);
                if (field != null) {
                    try {
                        Object value = FieldUtils.readField(field, entity);
                        if (value != null) {
                            FieldUtils.writeField(field, merged, value);
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException("Error copying non-persistent attribute value to merged instance", e);
                    }
                }
            }
        }

        return merged;
    } finally {
        CubaUtil.setSoftDeletion(softDeletion);
        CubaUtil.setOriginalSoftDeletion(softDeletion);
    }
}
 
Example 20
Source File: UnsafeUtils.java    From confucius-commons with Apache License 2.0 3 votes vote down vote up
/**
 * 获取对象字段的偏移量
 *
 * @param object
 *         对象实例
 * @param fieldName
 *         字段名称
 * @return 偏移量
 * @throws IllegalArgumentException
 *         在制定类型中无法通过字段名称获取时
 * @throws NullPointerException
 *         当参数为<code>null</code>时
 */
protected static long getObjectFieldOffset(Object object, String fieldName) throws IllegalArgumentException, NullPointerException {
    Class<?> type = object.getClass();
    Long offsetFromCache = getOffsetFromCache(type, fieldName);
    if (offsetFromCache != null) {
        return offsetFromCache;
    }
    Field field = FieldUtils.getField(type, fieldName, true);
    long offset = unsafe.objectFieldOffset(field);
    putOffsetFromCache(type, fieldName, offset);
    return offset;
}