Java Code Examples for org.springframework.util.ReflectionUtils#findField()

The following examples show how to use org.springframework.util.ReflectionUtils#findField() . 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
private void adjustFunctionForNativeEncodingIfNecessary(String outputDestinationName, FunctionInvocationWrapper function, int index) {
	if (function.isConsumer()) {
		return;
	}
	BindingProperties properties = this.serviceProperties.getBindingProperties(outputDestinationName);
	if (properties.getProducer() != null && properties.getProducer().isUseNativeEncoding()) {
		Field acceptedOutputMimeTypesField = ReflectionUtils
				.findField(FunctionInvocationWrapper.class, "acceptedOutputMimeTypes", String[].class);
		acceptedOutputMimeTypesField.setAccessible(true);
		try {
			String[] acceptedOutputMimeTypes = (String[]) acceptedOutputMimeTypesField.get(function);
			acceptedOutputMimeTypes[index] = "";
		}
		catch (Exception e) {
			// ignore
		}
	}
}
 
Example 2
@Test
public void requestMappingHandlerMapping() throws Exception {
	ApplicationContext context = loadConfig(WebFluxConfig.class);
	final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator");
	ReflectionUtils.makeAccessible(field);

	String name = "requestMappingHandlerMapping";
	RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
	assertNotNull(mapping);

	assertEquals(0, mapping.getOrder());

	PathPatternParser patternParser = mapping.getPathPatternParser();
	assertNotNull(patternParser);
	boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser);
	assertTrue(matchOptionalTrailingSlash);

	name = "webFluxContentTypeResolver";
	RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
	assertSame(resolver, mapping.getContentTypeResolver());

	ServerWebExchange exchange = MockServerWebExchange.from(get("/path").accept(MediaType.APPLICATION_JSON));
	assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), resolver.resolveMediaTypes(exchange));
}
 
Example 3
@Test
public void customPathMatchConfig() {
	ApplicationContext context = loadConfig(CustomPatchMatchConfig.class);
	final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator");
	ReflectionUtils.makeAccessible(field);

	String name = "requestMappingHandlerMapping";
	RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
	assertNotNull(mapping);

	PathPatternParser patternParser = mapping.getPathPatternParser();
	assertNotNull(patternParser);
	boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser);
	assertFalse(matchOptionalTrailingSlash);

	Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
	assertEquals(1, map.size());
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			map.keySet().iterator().next().getPatternsCondition().getPatterns());
}
 
Example 4
@Test
public void customPathMatchConfig() {
	ApplicationContext context = loadConfig(CustomPatchMatchConfig.class);
	final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator");
	ReflectionUtils.makeAccessible(field);

	String name = "requestMappingHandlerMapping";
	RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
	assertNotNull(mapping);

	PathPatternParser patternParser = mapping.getPathPatternParser();
	assertNotNull(patternParser);
	boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser);
	assertFalse(matchOptionalTrailingSlash);

	Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
	assertEquals(1, map.size());
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			map.keySet().iterator().next().getPatternsCondition().getPatterns());
}
 
Example 5
Source Project: spring4-understanding   File: Property.java    License: Apache License 2.0 6 votes vote down vote up
private Field getField() {
	String name = getName();
	if (!StringUtils.hasLength(name)) {
		return null;
	}
	Class<?> declaringClass = declaringClass();
	Field field = ReflectionUtils.findField(declaringClass, name);
	if (field == null) {
		// Same lenient fallback checking as in CachedIntrospectionResults...
		field = ReflectionUtils.findField(declaringClass,
				name.substring(0, 1).toLowerCase() + name.substring(1));
		if (field == null) {
			field = ReflectionUtils.findField(declaringClass,
					name.substring(0, 1).toUpperCase() + name.substring(1));
		}
	}
	return field;
}
 
Example 6
Source Project: summerframework   File: TestLock.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRefer() throws IllegalAccessException, InterruptedException {
    Field field = ReflectionUtils.findField(JavaConcurrentLockFactory.class, "lockCache");
    field.setAccessible(true);
    ConcurrentHashMap<String, WeakReference<Lock>> cache = (ConcurrentHashMap<String, WeakReference<Lock>>) field.get(javaConcurrentLockFactory);
    Assert.assertEquals(0,cache.size());
    // 强引用不会消失
    LockInstance lockTest = lockOperation.requireLock("test");
    int count=1000;
    for (int i = 0; i < count; i++) {
        lockOperation.requireLock("test"+i).lockThen(lock->{

        });
    }
    Assert.assertEquals(count+1,cache.entrySet().stream().filter(e->e.getValue().get()!=null).count());
    System.gc();
    Thread.sleep(1000);
    Assert.assertEquals(0+1,cache.entrySet().stream().filter(e->e.getValue().get()!=null).count());
    for (int i = 0; i < count; i++) {
        lockOperation.requireLock("test"+i).lockThen(lock->{

        });
    }
    Assert.assertEquals(count+1,cache.entrySet().stream().filter(e->e.getValue().get()!=null).count());
}
 
Example 7
Source Project: syncope   File: SchemaTypePanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<IColumn<SchemaTO, String>> getColumns() {
    final List<IColumn<SchemaTO, String>> columns = new ArrayList<>();

    for (String field : COL_NAMES.get(schemaType)) {
        Field clazzField = ReflectionUtils.findField(schemaType.getToClass(), field);

        if (clazzField != null && !clazzField.isSynthetic()) {
            if (clazzField.getType().equals(Boolean.class) || clazzField.getType().equals(boolean.class)) {
                columns.add(new BooleanPropertyColumn<>(new ResourceModel(field), field, field));
            } else {
                IColumn<SchemaTO, String> column = new PropertyColumn<SchemaTO, String>(
                        new ResourceModel(field), field, field) {

                    private static final long serialVersionUID = 3282547854226892169L;

                    @Override
                    public String getCssClass() {
                        String css = super.getCssClass();
                        if (Constants.KEY_FIELD_NAME.equals(field)) {
                            css = StringUtils.isBlank(css)
                                    ? "col-xs-1"
                                    : css + " col-xs-1";
                        }
                        return css;
                    }
                };
                columns.add(column);
            }
        }
    }

    return columns;
}
 
Example 8
private static Object getField(Object target, String name) {
	Field field = ReflectionUtils.findField(target.getClass(), name);
	if (field == null) {
		return null;
	}
	ReflectionUtils.makeAccessible(field);
	return ReflectionUtils.getField(field, target);
}
 
Example 9
@Test
public void SCF_GH_429ConfigurationTests() throws Exception {
	FunctionCatalog catalog = this.configureCatalog(MyFunction.class);
	FunctionInvocationWrapper function = catalog.lookup("beanFactoryAwareFunctionRegistryTests.MyFunction");
	assertThat(function).isNotNull();
	Field f = ReflectionUtils.findField(FunctionInvocationWrapper.class, "composed");
	f.setAccessible(true);
	boolean composed = (boolean) f.get(function);
	assertThat(composed).isFalse();
}
 
Example 10
@Override
@Nullable
protected FieldPropertyHandler getLocalPropertyHandler(String propertyName) {
	FieldPropertyHandler propertyHandler = this.fieldMap.get(propertyName);
	if (propertyHandler == null) {
		Field field = ReflectionUtils.findField(getWrappedClass(), propertyName);
		if (field != null) {
			propertyHandler = new FieldPropertyHandler(field);
			this.fieldMap.put(propertyName, propertyHandler);
		}
	}
	return propertyHandler;
}
 
Example 11
public String getUserField(Class type) {

        if (ReflectionUtils.findField(type, "userId") != null) {
            return "userId";
        }

        return "creatorId";
    }
 
Example 12
public void setTemporaryField(Object objectContainingField, String fieldName, Object fieldValue)
{
    if (log.isDebugEnabled())
    {
        log.debug("Overriding field '" + fieldName + "' on object " + objectContainingField + " to new value '" + fieldValue + "'");
    }
    
    // Extract the pristine value of the field we're going to mock.
    Field f = ReflectionUtils.findField(objectContainingField.getClass(), fieldName);
    
    if (f == null)
    {
        final String msg = "Object of type '" + objectContainingField.getClass().getSimpleName() + "' has no field named '" + fieldName + "'";
        if (log.isDebugEnabled())
        {
            log.debug(msg);
        }
        throw new IllegalArgumentException(msg);
    }
    
    ReflectionUtils.makeAccessible(f);
    Object pristineValue = ReflectionUtils.getField(f, objectContainingField);
    
    // and add it to the list.
    pristineFieldValues.add(new FieldValueOverride(objectContainingField, fieldName, pristineValue));
    
    // and set it on the object
    ReflectionUtils.setField(f, objectContainingField, fieldValue);
}
 
Example 13
@Before
public void setup() throws IllegalArgumentException, IllegalAccessException {
	MockitoAnnotations.initMocks(this);
	cfCertTruster = new CloudFoundryCertificateTruster();
	Field envField = ReflectionUtils.findField(CloudFoundryCertificateTruster.class, "env");
	ReflectionUtils.makeAccessible(envField);
	ReflectionUtils.setField(envField, cfCertTruster, env);
	Field sslCertTrusterField = ReflectionUtils.findField(CloudFoundryCertificateTruster.class,
			"sslCertificateTruster");
	ReflectionUtils.makeAccessible(sslCertTrusterField);
	ReflectionUtils.setField(sslCertTrusterField, cfCertTruster, sslCertTruster);
}
 
Example 14
private void setLayout(LoggerContext loggerContext,OutputStreamAppender outputStreamAppender){
    Encoder<?> encoder = outputStreamAppender.getEncoder();
    if (encoder instanceof LayoutWrappingEncoder) {
        TraceIdPatternLogbackLayout traceIdLayOut = new TraceIdPatternLogbackLayout();
        traceIdLayOut.setContext(loggerContext);
        traceIdLayOut.setPattern(getLogBackPattern());
        traceIdLayOut.start();
        Field field = ReflectionUtils.findField(encoder.getClass(), "layout");
        field.setAccessible(true);
        ReflectionUtils.setField(field, encoder, traceIdLayOut);
    }
}
 
Example 15
Source Project: bowman   File: ReflectionSupport.java    License: Apache License 2.0 4 votes vote down vote up
private static Field getIdField(Class<?> clazz) {
	Method idAccessor = getIdAccessor(clazz);
	return ReflectionUtils.findField(clazz, HalSupport.toLinkName(idAccessor.getName()));
}
 
Example 16
Source Project: sdk-java   File: DiscoveryApiITest.java    License: MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, Object> getOtherProperties(final Object object) {
  Field otherProperties = ReflectionUtils.findField(object.getClass(), "otherProperties");
  ReflectionUtils.makeAccessible(otherProperties);
  return (Map<String, Object>) ReflectionUtils.getField(otherProperties, object);
}
 
Example 17
protected <T> T getField(Object target, String name) {
	Field field = ReflectionUtils.findField(target.getClass(), name);
	ReflectionUtils.makeAccessible(field);
	Object value = ReflectionUtils.getField(field, target);
	return (T) value;
}
 
Example 18
Source Project: egeria   File: GlossaryViewOmasBaseTest.java    License: Apache License 2.0 4 votes vote down vote up
public void before(GlossaryViewOMAS underTest) throws Exception{
    MockitoAnnotations.initMocks(this);
    when(instanceHandler.getRepositoryHandler(eq(USER_ID), eq(SERVER_NAME), anyString())).thenReturn(repositoryHandler);
    when(instanceHandler.getRepositoryConnector(eq(USER_ID), eq(SERVER_NAME), anyString())).thenReturn(repositoryConnector);
    when(repositoryConnector.getRepositoryHelper()).thenReturn(repositoryHelper);

    when(repositoryHelper.getTypeDefByName(anyString(), eq(GLOSSARY_TYPE_NAME))).thenReturn(glossaryTypeDef);
    when(glossaryTypeDef.getGUID()).thenReturn(GLOSSARY_TYPE_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(CATEGORY_TYPE_NAME))).thenReturn(categoryTypeDef);
    when(categoryTypeDef.getGUID()).thenReturn(CATEGORY_TYPE_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(TERM_TYPE_NAME))).thenReturn(termTypeDef);
    when(termTypeDef.getGUID()).thenReturn(TERM_TYPE_GUID);

    when(repositoryHelper.getTypeDefByName(anyString(), eq(CATEGORY_HIERARCHY_LINK_RELATIONSHIP_NAME))).thenReturn(categoryHierarchyLinkRelationshipTypeDef);
    when(categoryHierarchyLinkRelationshipTypeDef.getGUID()).thenReturn(CATEGORY_HIERARCHY_LINK_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(EXTERNALLY_SOURCED_GLOSSARY_RELATIONSHIP_NAME))).thenReturn(externallySourcedGlossaryRelationshipTypeDef);
    when(externallySourcedGlossaryRelationshipTypeDef.getGUID()).thenReturn(EXTERNALLY_SOURCED_GLOSSARY_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(CATEGORY_ANCHOR_RELATIONSHIP_NAME))).thenReturn(categoryAnchorRelationshipTypeDef);
    when(categoryAnchorRelationshipTypeDef.getGUID()).thenReturn(CATEGORY_ANCHOR_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(TERM_ANCHOR_RELATIONSHIP_NAME))).thenReturn(termAnchorRelationshipTypeDef);
    when(termAnchorRelationshipTypeDef.getGUID()).thenReturn(TERM_ANCHOR_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(TERM_CATEGORIZATION_RELATIONSHIP_NAME))).thenReturn(termCategorizationRelationshipTypeDef);
    when(termCategorizationRelationshipTypeDef.getGUID()).thenReturn(TERM_CATEGORIZATION_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(LIBRARY_CATEGORY_REFERENCE_RELATIONSHIP_NAME))).thenReturn(libraryCategoryReferenceRelationshipTypeDef);
    when(libraryCategoryReferenceRelationshipTypeDef.getGUID()).thenReturn(LIBRARY_CATEGORY_REFERENCE_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(LIBRARY_TERM_REFERENCE_RELATIONSHIP_NAME))).thenReturn(libraryTermReferenceRelationshipTypeDef);
    when(libraryTermReferenceRelationshipTypeDef.getGUID()).thenReturn(LIBRARY_TERM_REFERENCE_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(RELATED_TERM_RELATIONSHIP_NAME))).thenReturn(relatedTermRelationshipTypeDef);
    when(relatedTermRelationshipTypeDef.getGUID()).thenReturn(RELATED_TERM_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(SYNONYM_RELATIONSHIP_NAME))).thenReturn(synonymRelationshipTypeDef);
    when(synonymRelationshipTypeDef.getGUID()).thenReturn(SYNONYM_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(ANTONYM_RELATIONSHIP_NAME))).thenReturn(antonymRelationshipTypeDef);
    when(antonymRelationshipTypeDef.getGUID()).thenReturn(ANTONYM_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(PREFERRED_TERM_RELATIONSHIP_NAME))).thenReturn(preferredTermRelationshipTypeDef);
    when(preferredTermRelationshipTypeDef.getGUID()).thenReturn(PREFERRED_TERM_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(REPLACEMENT_TERM_RELATIONSHIP_NAME))).thenReturn(replacementTermRelationshipTypeDef);
    when(replacementTermRelationshipTypeDef.getGUID()).thenReturn(REPLACEMENT_TERM_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(TRANSLATION_RELATIONSHIP_NAME))).thenReturn(translationRelationshipTypeDef);
    when(translationRelationshipTypeDef.getGUID()).thenReturn(TRANSLATION_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(IS_A_RELATIONSHIP_NAME))).thenReturn(isARelationshipTypeDef);
    when(isARelationshipTypeDef.getGUID()).thenReturn(IS_A_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(VALID_VALUE_RELATIONSHIP_NAME))).thenReturn(validValueRelationshipTypeDef);
    when(validValueRelationshipTypeDef.getGUID()).thenReturn(VALID_VALUE_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(USED_IN_CONTEXT_RELATIONSHIP_NAME))).thenReturn(usedInContextRelationshipTypeDef);
    when(usedInContextRelationshipTypeDef.getGUID()).thenReturn(USED_IN_CONTEXT_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(SEMANTIC_ASSIGNMENT_RELATIONSHIP_NAME))).thenReturn(semanticAssignmentRelationshipTypeDef);
    when(semanticAssignmentRelationshipTypeDef.getGUID()).thenReturn(SEMANTIC_ASSIGNMENT_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(TERM_HAS_A_RELATIONSHIP_NAME))).thenReturn(termHasARelationshipTypeDef);
    when(termHasARelationshipTypeDef.getGUID()).thenReturn(TERM_HAS_A_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(TERM_IS_A_TYPE_OF_RELATIONSHIP_NAME))).thenReturn(termIsATypeOfRelationshipTypeDef);
    when(termIsATypeOfRelationshipTypeDef.getGUID()).thenReturn(TERM_IS_A_TYPE_OF_RELATIONSHIP_GUID);
    when(repositoryHelper.getTypeDefByName(anyString(), eq(TERM_TYPED_BY_RELATIONSHIP_NAME))).thenReturn(termTypedByRelationshipTypeDef);
    when(termTypedByRelationshipTypeDef.getGUID()).thenReturn(TERM_TYPED_BY_RELATIONSHIP_GUID);

    Field instanceHandlerField = ReflectionUtils.findField(OMRSClient.class, "instanceHandler");
    instanceHandlerField.setAccessible(true);
    ReflectionUtils.setField(instanceHandlerField, underTest, instanceHandler);
    instanceHandlerField.setAccessible(false);

    glossaries.add(createGlossary("glossary-1"));
    glossaries.add(createGlossary("glossary-2"));
    glossaries.add(createGlossary("glossary-3"));

    categories.add(createCategory("category-1"));
    categories.add(createCategory("category-2"));
    categories.add(createCategory("category-3"));

    terms.add(createTerm("term-1"));
    terms.add(createTerm("term-2"));
    terms.add(createTerm("term-3"));
    terms.add(createTerm("term-4"));
    terms.add(createTerm("term-5"));

    externalGlossaryLink = createExternalGlossaryLink("external-glossary-link-1");
}
 
Example 19
@Override
public PropertyAccess buildPropertyAccess(Class containerJavaType, String propertyName) {
    Method readMethod = ReflectionUtils.findMethod(containerJavaType, NameUtils.getGetterName(propertyName));
    if(readMethod == null) {
        throw new IllegalStateException("TraitPropertyAccessStrategy used on property ["+propertyName+"] of class ["+containerJavaType.getName()+"] that is not provided by a trait!");
    }
    else {

        Traits.Implemented traitImplemented = readMethod.getAnnotation(Traits.Implemented.class);
        final String traitFieldName;
        if(traitImplemented == null) {
            Traits.TraitBridge traitBridge = readMethod.getAnnotation(Traits.TraitBridge.class);
            if(traitBridge != null) {
                traitFieldName = getTraitFieldName(traitBridge.traitClass(), propertyName);
            }
            else {
                throw new IllegalStateException("TraitPropertyAccessStrategy used on property ["+propertyName+"] of class ["+containerJavaType.getName()+"] that is not provided by a trait!");
            }
        }
        else {
            traitFieldName = getTraitFieldName(readMethod.getDeclaringClass(), propertyName);
        }


        Field field = ReflectionUtils.findField(containerJavaType, traitFieldName );
        final Getter getter;
        final Setter setter;
        if(field == null) {
            getter = new GetterMethodImpl(containerJavaType, propertyName, readMethod);
            Method writeMethod = ReflectionUtils.findMethod(containerJavaType, NameUtils.getSetterName(propertyName), readMethod.getReturnType());
            setter = new SetterMethodImpl(containerJavaType, propertyName, writeMethod);
        }
        else {

            getter = new GetterFieldImpl(containerJavaType, propertyName, field );
            setter = new SetterFieldImpl(containerJavaType, propertyName,field);
        }

        return new PropertyAccess() {
            @Override
            public PropertyAccessStrategy getPropertyAccessStrategy() {
                return TraitPropertyAccessStrategy.this;
            }

            @Override
            public Getter getGetter() {
                return getter;
            }

            @Override
            public Setter getSetter() {
                return setter;
            }
        };
    }
}
 
Example 20
private void testIsDefault(String fieldName, boolean expectedValue) {

		Field objectField = ReflectionUtils.findField(getClass(), fieldName);

		NacosInjected nacosInjected = objectField.getAnnotation(NacosInjected.class);

		NacosProperties nacosProperties = nacosInjected.properties();

		Assert.assertEquals(expectedValue, NacosUtils.isDefault(nacosProperties));

	}