List of usage examples for org.springframework.util ReflectionUtils makeAccessible
@SuppressWarnings("deprecation") public static void makeAccessible(Field field)
From source file:org.kuali.student.common.spring.WebServiceAwareSpringBeanPostProcessor.java
private void injectServiceReference(Object bean, String beanName, Field field, Object service, String message) throws IllegalArgumentException, IllegalAccessException { String fieldName = field.getName(); String setterMethodName = "set" + StringUtils.capitalize(fieldName); Class<? extends Object> beanClass = bean.getClass(); Class<?> fieldType = field.getType(); try {/*from w w w.ja v a 2 s. c om*/ /* * We use the set method because even though we can reach in and set the bean * if it is final we still get an exception. * This way it will always work. * And since the bean's are presently being wired using XML the setters will exist. * */ Method setterMethod = beanClass.getMethod(setterMethodName, field.getType()); ReflectionUtils.invokeMethod(setterMethod, bean, service); log.warn("RESOLVED: beanName = " + beanName + ", fieldName = " + field.getName() + ", fieldType = " + fieldType.getName() + message); } catch (IllegalArgumentException e) { log.warn("set error", e); } catch (SecurityException e) { log.warn("set error", e); } catch (NoSuchMethodException e) { // try the field ReflectionUtils.makeAccessible(field); field.set(bean, service); log.warn("RESOLVED: beanName = " + beanName + ", fieldName = " + field.getName() + ", fieldType = " + fieldType.getName() + message); } }
From source file:org.orcid.api.common.writer.citeproc.WorkToCiteprocTranslator.java
/** * Extract the bibtex and turn into CSL Adds in DOI and URL from metadata if * missing Horrible use of reflection to shorten hyperauthorship. It will * strip anything above 20 authors down to the primary author and 'et all'. * //w w w . j av a 2 s . c om * @param work * @param abreviate * @return */ private CSLItemData translateFromBibtexCitation(Work work, boolean abreviate) { try { System.out.println("----"); System.out.println(work.getWorkCitation().getCitation()); System.out.println("----"); BibTeXConverter conv = new BibTeXConverter(); BibTeXDatabase db = conv.loadDatabase(IOUtils.toInputStream(work.getWorkCitation().getCitation())); Map<String, CSLItemData> cids = conv.toItemData(db); if (cids.size() == 1) { CSLItemData item = cids.values().iterator().next(); // FOR REASONS UNKNOWN, CITEPROC WILL SOMETIMES generate // multiple authors not a literal. if (abreviate) { if (item.getAuthor().length > 20) { CSLName[] abrev = Arrays.copyOf(item.getAuthor(), 1); abrev[0] = new CSLNameBuilder() .literal(abrev[0].getGiven() + " " + abrev[0].getFamily() + " " + "et all.") .build(); ReflectionUtils.makeAccessible(authorField); ReflectionUtils.setField(authorField, item, abrev); } for (int i = 0; i < item.getAuthor().length; i++) { if (item.getAuthor()[i].getLiteral() != null && item.getAuthor()[i].getLiteral().length() > 200) { ReflectionUtils.makeAccessible(literalField); ReflectionUtils.setField(literalField, item.getAuthor()[i], StringUtils.abbreviate(item.getAuthor()[i].getLiteral(), 200)); } } } if (item.getDOI() == null) { String doi = extractID(work, WorkExternalIdentifierType.DOI); if (doi != null) { ReflectionUtils.makeAccessible(doiField); ReflectionUtils.setField(doiField, item, doi); } } if (item.getURL() == null) { if (extractID(work, WorkExternalIdentifierType.URI) != null) { ReflectionUtils.makeAccessible(urlField); ReflectionUtils.setField(urlField, item, extractID(work, WorkExternalIdentifierType.URI)); } else if (item.getDOI() != null) { ReflectionUtils.makeAccessible(urlField); ReflectionUtils.setField(urlField, item, item.getDOI()); } else if (extractID(work, WorkExternalIdentifierType.HANDLE) != null) { ReflectionUtils.makeAccessible(urlField); ReflectionUtils.setField(urlField, item, extractID(work, WorkExternalIdentifierType.HANDLE)); } } return item; } else throw new ParseException("Invalid Citation count"); } catch (IOException | ParseException e) { return null; } }
From source file:org.springframework.aop.framework.ObjenesisCglibAopProxy.java
@Override @SuppressWarnings("unchecked") protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) { Class<?> proxyClass = enhancer.createClass(); Object proxyInstance = null;/*from ww w .j a v a 2 s.c om*/ if (objenesis.isWorthTrying()) { try { proxyInstance = objenesis.newInstance(proxyClass, enhancer.getUseCache()); } catch (Throwable ex) { logger.debug("Unable to instantiate proxy using Objenesis, " + "falling back to regular proxy construction", ex); } } if (proxyInstance == null) { // Regular instantiation via default constructor... try { Constructor<?> ctor = (this.constructorArgs != null ? proxyClass.getDeclaredConstructor(this.constructorArgTypes) : proxyClass.getDeclaredConstructor()); ReflectionUtils.makeAccessible(ctor); proxyInstance = (this.constructorArgs != null ? ctor.newInstance(this.constructorArgs) : ctor.newInstance()); } catch (Throwable ex) { throw new AopConfigException("Unable to instantiate proxy using Objenesis, " + "and regular proxy instantiation via default constructor fails as well", ex); } } ((Factory) proxyInstance).setCallbacks(callbacks); return proxyInstance; }
From source file:org.springframework.batch.integration.chunk.RemoteChunkHandlerFactoryBean.java
private static Object getField(Object target, String name) { Assert.notNull(target, "Target object must not be null"); Field field = ReflectionUtils.findField(target.getClass(), name); if (field == null) { if (logger.isDebugEnabled()) { logger.debug("Could not find field [" + name + "] on target [" + target + "]"); }//from w w w . j av a2s. co m return null; } if (logger.isDebugEnabled()) { logger.debug("Getting field [" + name + "] from target [" + target + "]"); } ReflectionUtils.makeAccessible(field); return ReflectionUtils.getField(field, target); }
From source file:org.springframework.beans.BeanUtils.java
/** * Convenience method to instantiate a class using the given constructor. * <p>Note that this method tries to set the constructor accessible if given a * non-accessible (that is, non-public) constructor, and supports Kotlin classes * with optional parameters and default values. * @param ctor the constructor to instantiate * @param args the constructor arguments to apply (use {@code null} for an unspecified * parameter if needed for Kotlin classes with optional parameters and default values) * @return the new instance/*from ww w . j a v a 2 s . c o m*/ * @throws BeanInstantiationException if the bean cannot be instantiated * @see Constructor#newInstance */ public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException { Assert.notNull(ctor, "Constructor must not be null"); try { ReflectionUtils.makeAccessible(ctor); return (KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ? KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args)); } catch (InstantiationException ex) { throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex); } catch (IllegalAccessException ex) { throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex); } catch (IllegalArgumentException ex) { throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex); } catch (InvocationTargetException ex) { throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException()); } }
From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java
/** * Invoke the specified custom init method on the given bean. * Called by invokeInitMethods./* w w w .j av a2 s . c o m*/ * <p>Can be overridden in subclasses for custom resolution of init * methods with arguments. * @see #invokeInitMethods */ protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { String initMethodName = mbd.getInitMethodName(); Assert.state(initMethodName != null, "No init method set"); final Method initMethod = (mbd.isNonPublicAccessAllowed() ? BeanUtils.findMethod(bean.getClass(), initMethodName) : ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName)); if (initMethod == null) { if (mbd.isEnforceInitMethod()) { throw new BeanDefinitionValidationException("Couldn't find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'"); } else { if (logger.isTraceEnabled()) { logger.trace("No default init method named '" + initMethodName + "' found on bean with name '" + beanName + "'"); } // Ignore non-existent default lifecycle methods. return; } } if (logger.isTraceEnabled()) { logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'"); } if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { ReflectionUtils.makeAccessible(initMethod); return null; }); try { AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> initMethod.invoke(bean), getAccessControlContext()); } catch (PrivilegedActionException pae) { InvocationTargetException ex = (InvocationTargetException) pae.getException(); throw ex.getTargetException(); } } else { try { ReflectionUtils.makeAccessible(initMethod); initMethod.invoke(bean); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } }
From source file:org.springframework.beans.factory.support.DisposableBeanAdapter.java
/** * Invoke the specified custom destroy method on the given bean. * <p>This implementation invokes a no-arg method if found, else checking * for a method with a single boolean argument (passing in "true", * assuming a "force" parameter), else logging an error. *//*from w w w . j a v a2 s.c o m*/ private void invokeCustomDestroyMethod(final Method destroyMethod) { Class<?>[] paramTypes = destroyMethod.getParameterTypes(); final Object[] args = new Object[paramTypes.length]; if (paramTypes.length == 1) { args[0] = Boolean.TRUE; } if (logger.isDebugEnabled()) { logger.debug("Invoking destroy method '" + this.destroyMethodName + "' on bean with name '" + this.beanName + "'"); } try { if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { ReflectionUtils.makeAccessible(destroyMethod); return null; }); try { AccessController.doPrivileged( (PrivilegedExceptionAction<Object>) () -> destroyMethod.invoke(bean, args), acc); } catch (PrivilegedActionException pax) { throw (InvocationTargetException) pax.getException(); } } else { ReflectionUtils.makeAccessible(destroyMethod); destroyMethod.invoke(bean, args); } } catch (InvocationTargetException ex) { String msg = "Invocation of destroy method '" + this.destroyMethodName + "' failed on bean with name '" + this.beanName + "'"; if (logger.isDebugEnabled()) { logger.warn(msg, ex.getTargetException()); } else { logger.warn(msg + ": " + ex.getTargetException()); } } catch (Throwable ex) { logger.error("Couldn't invoke destroy method '" + this.destroyMethodName + "' on bean with name '" + this.beanName + "'", ex); } }
From source file:org.springframework.beans.TypeConverterDelegate.java
private Object attemptToConvertStringToEnum(Class<?> requiredType, String trimmedValue, Object currentConvertedValue) { Object convertedValue = currentConvertedValue; if (Enum.class == requiredType && this.targetObject != null) { // target type is declared as raw enum, treat the trimmed value as <enum.fqn>.FIELD_NAME int index = trimmedValue.lastIndexOf("."); if (index > -1) { String enumType = trimmedValue.substring(0, index); String fieldName = trimmedValue.substring(index + 1); ClassLoader cl = this.targetObject.getClass().getClassLoader(); try { Class<?> enumValueType = ClassUtils.forName(enumType, cl); Field enumField = enumValueType.getField(fieldName); convertedValue = enumField.get(null); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("Enum class [" + enumType + "] cannot be loaded", ex); }// w ww. j av a2 s .c o m } catch (Throwable ex) { if (logger.isTraceEnabled()) { logger.trace("Field [" + fieldName + "] isn't an enum value for type [" + enumType + "]", ex); } } } } if (convertedValue == currentConvertedValue) { // Try field lookup as fallback: for JDK 1.5 enum or custom enum // with values defined as static fields. Resulting value still needs // to be checked, hence we don't return it right away. try { Field enumField = requiredType.getField(trimmedValue); ReflectionUtils.makeAccessible(enumField); convertedValue = enumField.get(null); } catch (Throwable ex) { if (logger.isTraceEnabled()) { logger.trace("Field [" + convertedValue + "] isn't an enum value", ex); } } } return convertedValue; }
From source file:org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.java
private static boolean isBuilt(AuthenticationManagerBuilder builder) { Method configurers = ReflectionUtils.findMethod(AbstractConfiguredSecurityBuilder.class, "getConfigurers"); Method unbuilt = ReflectionUtils.findMethod(AbstractConfiguredSecurityBuilder.class, "isUnbuilt"); ReflectionUtils.makeAccessible(configurers); ReflectionUtils.makeAccessible(unbuilt); return !((Collection<?>) ReflectionUtils.invokeMethod(configurers, builder)).isEmpty() || !((Boolean) ReflectionUtils.invokeMethod(unbuilt, builder)); }
From source file:org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainer.java
@SuppressWarnings("unchecked") private List<BoundChannel> extractChannels() { Field channelsField = ReflectionUtils.findField(Undertow.class, "channels"); ReflectionUtils.makeAccessible(channelsField); return (List<BoundChannel>) ReflectionUtils.getField(channelsField, this.undertow); }