List of usage examples for java.lang.reflect Field isAccessible
@Deprecated(since = "9") public boolean isAccessible()
From source file:io.gravitee.management.service.processor.ApiSynchronizationProcessor.java
public boolean processCheckSynchronization(ApiEntity deployedApi, ApiEntity apiToDeploy) { Class<ApiEntity> cl = ApiEntity.class; List<Object> requiredFieldsDeployedApi = new ArrayList<Object>(); List<Object> requiredFieldsApiToDeploy = new ArrayList<Object>(); for (Field f : cl.getDeclaredFields()) { if (f.getAnnotation(DeploymentRequired.class) != null) { boolean previousAccessibleState = f.isAccessible(); f.setAccessible(true);//from ww w .j a v a 2s . com try { requiredFieldsDeployedApi.add(f.get(deployedApi)); requiredFieldsApiToDeploy.add(f.get(apiToDeploy)); } catch (Exception e) { LOGGER.error("Error access API required deployment fields", e); } finally { f.setAccessible(previousAccessibleState); } } } try { String requiredFieldsDeployedApiDefinition = objectMapper.writeValueAsString(requiredFieldsDeployedApi); String requiredFieldsApiToDeployDefinition = objectMapper.writeValueAsString(requiredFieldsApiToDeploy); return requiredFieldsDeployedApiDefinition.equals(requiredFieldsApiToDeployDefinition); } catch (Exception e) { LOGGER.error("Unexpected error while generating API deployment required fields definition", e); return false; } }
From source file:com.rosenvold.spring.SpringContextAnalyzer.java
private Object getFieldValue(Object instance, Field field) { if (!field.isAccessible()) field.setAccessible(true);//from w ww . j a v a 2s . c om try { return field.get(instance); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
From source file:com.github.fharms.camel.entitymanager.CamelEntityManagerHandler.java
/** * Scan all fields for the {@link PersistenceContext} annotation and verify the type and return * a list of annotated fields. If the field is also annotated with {@link IgnoreCamelEntityManager} * it will be ignored from the list//w w w .j a va 2 s . c o m * * @param bean Name of the bean to scan for annotation * @return List of fields annotated with {@link PersistenceContext} */ private List<Field> getAnnotatedFields(Object bean) throws IllegalAccessException { List<Field> annotatedFields = new ArrayList<>(); if (bean == null) { return annotatedFields; } Field[] declaredFields = bean.getClass().getDeclaredFields(); for (Field field : declaredFields) { boolean currentAccessible = field.isAccessible(); field.setAccessible(true); if (EntityManager.class.isAssignableFrom(field.getType()) && (field.isAnnotationPresent(PersistenceContext.class)) && (!field.isAnnotationPresent(IgnoreCamelEntityManager.class)) && (field.get(bean) != null)) { annotatedFields.add(field); } field.setAccessible(currentAccessible); } return annotatedFields; }
From source file:fr.mtlx.odm.ClassAssistant.java
public <V> void setProperty(final String propertyName, final T entry, final Collection<V> multipleValues) throws MappingException { @SuppressWarnings("unchecked") Class<T> c = (Class<T>) checkNotNull(entry).getClass(); final AttributeMetadata meta = metadata.getAttributeMetadata(propertyName); if (meta == null) { throw new MappingException(format("propertyName: unknown property %s", propertyName)); }/*from w w w . j a va 2 s. c o m*/ if (!meta.isMultivalued()) { throw new MappingException(format("propertyName: single valued property %s", propertyName)); } final Collection<?> targetValues; targetValues = buildCollection(meta.getCollectionType(), meta.getObjectType(), multipleValues); try { PropertyUtils.setProperty(entry, propertyName, targetValues); } catch (IllegalAccessException | InvocationTargetException e) { throw new MappingException(e); } catch (NoSuchMethodException e) { try { doWithFields(c, (final Field f) -> { boolean secured = !f.isAccessible(); if (secured) { f.setAccessible(true); } f.set(entry, targetValues); if (secured) { f.setAccessible(false); } }, (final Field field) -> { final int modifiers = field.getModifiers(); return !isStatic(modifiers) && (field.getName() == null ? propertyName == null : field.getName().equals(propertyName)); }); } catch (SecurityException | IllegalArgumentException e1) { throw new MappingException(e1); } } }
From source file:org.openinfinity.core.aspect.MultiTenantAspect.java
/** * Injection of tenant id will be done based on the <code>org.openinfinity.core.annotation.MultiTenant</code> annotation on method level. After injection of the tenant id * <code>org.openinfinity.core.domain.entity.MultiTenantBaseEntity</code> can be used to retrieve the actual tenant id. <code>org.openinfinity.core.domain.entity.MultiTenantBaseEntity</code> * can be extended by <code>org.openinfinity.core.domain.entity.MultiTenantBaseEntity</code>. * /* w ww. ja va 2 s. c o m*/ * @param method Represents the method to be executed when exposing <code>org.openinfinity.core.annotation.MultiTenant</code> metadata to it. * @param multiTenant Represents the annotation which executed by the aspect. * @return Object Represents the original arguments for the method with injected tenant id. * @throws Throwable Represents the occurred exception during the execution of the aspect. */ @Around("multiTenantMethod() && @annotation(multiTenant)") public Object populateTenantIdToMultiTenantEntity(ProceedingJoinPoint method, MultiTenant multiTenant) throws Throwable { if (LOGGER.isDebugEnabled()) LOGGER.debug("MultiTenantAspect.populateTenantIdToMultiTenantEntity initialized."); SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication instanceof Identity) { Identity identity = (Identity) authentication; Object[] arguments = method.getArgs(); for (Object object : arguments) { if (object instanceof MultiTenantBaseEntity) { if (LOGGER.isDebugEnabled()) LOGGER.debug( "MultiTenantAspect.populateTenantIdToMultiTenantEntity arguments is istance of MultiTenantBaseEntity."); MultiTenantBaseEntity<?, ?, ?> multiTenantBaseEntity = (MultiTenantBaseEntity<?, ?, ?>) object; Object tenantId = identity.getTenantPrincipal().getId(); Field tenantIdField = multiTenantBaseEntity.getClass().getField(TENANT_ID_FIELD); if (!tenantIdField.isAccessible()) { tenantIdField.setAccessible(true); } Object convertedTenantId = typeConverter.convert(tenantId); if (tenantIdField.getType().isAssignableFrom(convertedTenantId.getClass())) { if (LOGGER.isDebugEnabled()) LOGGER.debug( "MultiTenantAspect.populateTenantIdToMultiTenantEntity tenant id is assignable from [" + convertedTenantId.getClass().getName() + "."); ReflectionUtils.setField(tenantIdField, multiTenantBaseEntity, convertedTenantId); if (LOGGER.isInfoEnabled()) LOGGER.info("MultiTenantAspect.populateTenantIdToMultiTenantEntity injected tenant id [" + convertedTenantId.toString() + "] to the entity."); } else { ExceptionUtil.throwSystemException("Field [" + tenantIdField.getType().getName() + "] is not assignable from [" + convertedTenantId.getClass().getName()); } } } } return method.proceed(); }
From source file:in.hatimi.nosh.support.CmdLineManager.java
private boolean injectImpl(Object target, Field field, Object value) { try {/* ww w. j a va2s.c o m*/ boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } field.set(target, value); if (!accessible) { field.setAccessible(false); } return true; } catch (Exception exep) { return false; } }
From source file:org.openmrs.module.metadatadeploy.handler.impl.ConceptDeployHandler.java
/** * OpenMRS doesn't allow direct access to concept.names, this hacks around it * @param concept/*from w w w.j a v a2 s.c om*/ * @return */ private Collection<ConceptName> getConceptNamesCollection(Concept concept) { try { Field names = Concept.class.getDeclaredField("names"); boolean previousFieldAccessibility = names.isAccessible(); names.setAccessible(true); Collection<ConceptName> childCollection = (Collection<ConceptName>) names.get(concept); names.setAccessible(previousFieldAccessibility); return childCollection; } catch (NoSuchFieldException e) { throw new APIException("unaccessible getter method for concept.names"); } catch (IllegalAccessException e) { throw new APIException("unaccessible getter method for concept.names"); } }
From source file:com.flipkart.flux.client.intercept.WorkflowInterceptor.java
private String checkForCorrelationId(Object[] arguments) throws IllegalAccessException { final String[] correlationId = { null }; /* Iterate over given arguments to find if there is any argument that has a field marked with <code>CorrelationId</code> */ for (Object anArgument : arguments) { final Field[] allFields = anArgument.getClass().getDeclaredFields(); /* Search for any field which is of type String and has a CorrelationId annotation */ final Optional<Field> possibleAnnotatedField = Arrays.stream(allFields) .filter(field -> String.class.isAssignableFrom(field.getType())) .filter(field -> field.getAnnotationsByType(CorrelationId.class).length > 0).findAny(); /* If we have a field that matches above criteria, we populate the correlationId variable and break */ if (possibleAnnotatedField.isPresent()) { final Field correlationIdAnnotatedField = possibleAnnotatedField.get(); final boolean originalAccessibility = correlationIdAnnotatedField.isAccessible(); if (!originalAccessibility) { correlationIdAnnotatedField.setAccessible(true); }//from w w w .j a va 2 s . c om try { correlationId[0] = (String) correlationIdAnnotatedField.get(anArgument); break; } finally { if (!originalAccessibility) { correlationIdAnnotatedField.setAccessible(false); } } } } return correlationId[0]; }
From source file:org.springframework.data.keyvalue.riak.RiakMappedClass.java
private void initFields() { ReflectionUtils.doWithFields(this.clazz, new FieldCallback() { @Override//from w w w. j a v a2 s . c om public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { if (!field.isAccessible()) ReflectionUtils.makeAccessible(field); if (field.isAnnotationPresent(Transient.class) || field.isSynthetic() || field.getModifiers() == Modifier.FINAL || field.getModifiers() == Modifier.TRANSIENT) { return; } // Field can only have one of these, if more than one throw an // error List<Annotation> annots = org.springframework.data.keyvalue.riak.util.AnnotationUtils .getFoundAnnotation(Id.class, Column.class, Embedded.class, Version.class, ManyToOne.class, OneToMany.class, Basic.class); // Probably allow auto generation at some point, but for now // have to add one of the annotations if (annots.size() > 1) throw new IllegalArgumentException(String.format( "The field %s must have only one of the following annotations: " + "@Id, @Basic, @Column, @Embedded, @Version, @ManyToOne, @OneToMany", field.getName())); Annotation annot = annots.get(0); if (annot.annotationType().equals(Id.class)) RiakMappedClass.this.id = field; // Create a new mapped field here and then add to a list of // property MappedFields propertyFields.add(new RiakMappedField(field, annot)); } }); Map<Class<? extends Annotation>, Annotation> fieldAnnotMap = new HashMap<Class<? extends Annotation>, Annotation>(); for (Class<? extends Annotation> a : entityAnnotations) { Target target = a.getAnnotation(Target.class); if (target != null && (ArrayUtils.contains(target.value(), ElementType.FIELD) || ArrayUtils.contains(target.value(), ElementType.METHOD))) { Annotation fieldAnnot; if ((fieldAnnot = this.clazz.getAnnotation(a)) != null) { fieldAnnotMap.put(a, fieldAnnot); } } } }
From source file:candr.yoclip.option.AbstractFieldOption.java
protected void set(final T bean, final Value<T> value) { final Field field = getField(); boolean resetFieldAccessibility = false; try {/*from ww w .j av a 2s . c om*/ if (!field.isAccessible()) { field.setAccessible(true); resetFieldAccessibility = true; } value.set(bean, field); } catch (Exception e) { if (e instanceof OptionsParseException) { throw (OptionsParseException) e; } throw new OptionsParseException("Error setting field " + getUniqueId(), e); } finally { if (resetFieldAccessibility) { field.setAccessible(false); } } }