@Override public void setApplicationContext(ApplicationContext context) { Field field = ReflectionUtils.findField(Context.class, "applicationContext"); field.setAccessible(true); ReflectionUtils.setField(field, this, context); Field field2 = ReflectionUtils.findField(Context.class, "coreContext"); field2.setAccessible(true); ReflectionUtils.setField(field2, this, context.getParentBeanFactory()); }
private EventTriggerCaller buildCaller(Class<?> domainClazz, String event) { Method method = ReflectionUtils.findMethod(domainClazz, event); if (method != null) { ReflectionUtils.makeAccessible(method); return new MethodCaller(method); } Field field = ReflectionUtils.findField(domainClazz, event); if (field != null) { ReflectionUtils.makeAccessible(field); return new FieldClosureCaller(field); } MetaMethod metaMethod = domainMetaClass.getMetaMethod(event, EMPTY_OBJECT_ARRAY); if (metaMethod != null) { return new MetaMethodCaller(metaMethod); } MetaProperty metaProperty = domainMetaClass.getMetaProperty(event); if (metaProperty != null) { return new MetaPropertyClosureCaller(metaProperty); } return null; }
@Override public Object accessValue(Object entity) { Assert.notNull(entity); Method method = ReflectionUtils.findMethod(entity.getClass(), this.getAccessMethodName(), String.class); return ReflectionUtils.invokeMethod(method, entity); }
private static List<LabelValue> makeList2(Class<? extends Enum> clazz) { List<LabelValue> list = new ArrayList<LabelValue>(); Method method = ReflectionUtils.findMethod(clazz, "values"); try { Object[] array = (Object[]) method.invoke(null); for (Object obj : array) { Method m = ReflectionUtils.findMethod(clazz, "getLabel"); String cnName = (String) m.invoke(obj); m = ReflectionUtils.findMethod(clazz, "name"); String name = (String) m.invoke(obj); LabelValue lv = new LabelValue(cnName, name); m = ReflectionUtils.findMethod(clazz, "isSelectList"); if (m != null) { boolean flag = (boolean) m.invoke(obj); lv.setListFlag(flag); } list.add(lv); } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return list; }
/* (non-Javadoc) */ @SuppressWarnings("unchecked") private <T> T getFieldValue( final Object source, final String fieldName, final Class<T> targetType) { Field field = ReflectionUtils.findField(source.getClass(), fieldName, targetType); ReflectionUtils.makeAccessible(field); return (T) ReflectionUtils.getField(field, source); }
/** * Discover a {@link StepExecution} as a field in the test case or create one if none is * available. * * @param testContext the current test context * @return a {@link StepExecution} */ protected StepExecution getStepExecution(TestContext testContext) { Object target; try { Method method = TestContext.class.getMethod(GET_TEST_INSTANCE_METHOD); target = ReflectionUtils.invokeMethod(method, testContext); } catch (NoSuchMethodException e) { throw new IllegalStateException( "No such method " + GET_TEST_INSTANCE_METHOD + " on provided TestContext", e); } ExtractorMethodCallback method = new ExtractorMethodCallback(StepExecution.class, "getStepExecution"); ReflectionUtils.doWithMethods(target.getClass(), method); if (method.getName() != null) { HippyMethodInvoker invoker = new HippyMethodInvoker(); invoker.setTargetObject(target); invoker.setTargetMethod(method.getName()); try { invoker.prepare(); return (StepExecution) invoker.invoke(); } catch (Exception e) { throw new IllegalArgumentException( "Could not create step execution from method: " + method.getName(), e); } } return MetaDataInstanceFactory.createStepExecution(); }
@Override protected Object retrieveAction( GroovyObject controller, String actionName, HttpServletResponse response) { Class<?> controllerClass = AopProxyUtils.ultimateTargetClass(controller); Method mAction = ReflectionUtils.findMethod( controllerClass, actionName, MethodGrailsControllerHelper.NOARGS); if (mAction != null) { ReflectionUtils.makeAccessible(mAction); if (mAction.getAnnotation(Action.class) != null) { return mAction; } } try { return controller.getProperty(actionName); } catch (MissingPropertyException mpe) { try { response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } catch (IOException e) { throw new ControllerExecutionException("I/O error sending 404 error", e); } } }
public static void update() { try { final String msg = "DatabaseSchemaUpdater: Begin"; log(msg); final String applicationName = CommonServiceLocator.getInstance().getAppName(); DAO dao = DAOConfigFactory.getInstance().getDAOFactory(applicationName).getDAO(); Method getConnectionManagerMethod = ReflectionUtils.findMethod(dao.getClass(), "getConnectionManager"); ReflectionUtils.makeAccessible(getConnectionManagerMethod); IConnectionManager connectionManager = (IConnectionManager) ReflectionUtils.invokeMethod(getConnectionManagerMethod, dao); Connection c = null; try { c = connectionManager.getConnection(); update(c); } finally { try { connectionManager.commit(); } catch (Exception e) { } connectionManager.closeConnection(); } } catch (Exception e) { final String msg = "DatabaseSchemaUpdater: Failed with " + e.getMessage(); log(msg); } }
public void visit(ASTNode[] nodes, SourceUnit source) { List<ClassNode> classes = source.getAST().getClasses(); AnnotationNode annotation = null; for (ClassNode clazz : classes) { annotation = findAnnotation(clazz); if (annotation != null) { break; } } if (annotation == null) { return; } int[] array = extractLineNumberArray(annotation); if (array != null) { LineNumberVisitor visitor = new LineNumberVisitor(array); for (ClassNode clazz : classes) { visitor.visitClass(clazz); } } String sourceName = extractSourceName(annotation); if (sourceName != null) { source.getAST().setDescription(sourceName); // source.name = sourceName Field field = ReflectionUtils.findField(SourceUnit.class, "name"); field.setAccessible(true); ReflectionUtils.setField(field, source, sourceName); } }
private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { inputStream.defaultReadObject(); Method method = ReflectionUtils.findMethod(this.provider.getType().getClass(), this.methodName); this.result = ReflectionUtils.invokeMethod(method, this.provider.getType()); }
public final Object invokeHandlerMethod( Method handlerMethod, Object handler, NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception { Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod); try { boolean debug = logger.isDebugEnabled(); for (String attrName : this.methodResolver.getActualSessionAttributeNames()) { Object attrValue = this.sessionAttributeStore.retrieveAttribute(webRequest, attrName); if (attrValue != null) { implicitModel.addAttribute(attrName, attrValue); } } for (Method attributeMethod : this.methodResolver.getModelAttributeMethods()) { Method attributeMethodToInvoke = BridgeMethodResolver.findBridgedMethod(attributeMethod); Object[] args = resolveHandlerArguments(attributeMethodToInvoke, handler, webRequest, implicitModel); if (debug) { logger.debug("Invoking model attribute method: " + attributeMethodToInvoke); } String attrName = AnnotationUtils.findAnnotation(attributeMethod, ModelAttribute.class).value(); if (!"".equals(attrName) && implicitModel.containsAttribute(attrName)) { continue; } ReflectionUtils.makeAccessible(attributeMethodToInvoke); Object attrValue = attributeMethodToInvoke.invoke(handler, args); if ("".equals(attrName)) { Class<?> resolvedType = GenericTypeResolver.resolveReturnType(attributeMethodToInvoke, handler.getClass()); attrName = Conventions.getVariableNameForReturnType( attributeMethodToInvoke, resolvedType, attrValue); } if (!implicitModel.containsAttribute(attrName)) { implicitModel.addAttribute(attrName, attrValue); } } Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel); if (debug) { logger.debug("Invoking request handler method: " + handlerMethodToInvoke); } ReflectionUtils.makeAccessible(handlerMethodToInvoke); return handlerMethodToInvoke.invoke(handler, args); } catch (IllegalStateException ex) { // Internal assertion failed (e.g. invalid signature): // throw exception with full handler method context... throw new HandlerMethodInvocationException(handlerMethodToInvoke, ex); } catch (InvocationTargetException ex) { // User-defined @ModelAttribute/@InitBinder/@RequestMapping method threw an exception... ReflectionUtils.rethrowException(ex.getTargetException()); return null; } }
/** * This method uses reflection to build a valid hash code. * * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This * means that it will throw a security exception if run under a security manager, if the * permissions are not set up correctly. It is also not as efficient as testing explicitly. * * <p>Transient members will not be used, as they are likely derived fields, and not part of the * value of the <code>Object</code>. * * <p>Static fields will not be tested. Superclass fields will be included. * * @param obj the object to create a <code>hashCode</code> for * @return the generated hash code, or zero if the given object is <code>null</code> */ public static int reflectionHashCode(Object obj) { if (obj == null) return 0; Class<?> targetClass = obj.getClass(); if (isArrayOfPrimitives(obj)) { // || ObjectUtils.isPrimitiveOrWrapper(targetClass)) { return ObjectUtils.nullSafeHashCode(obj); } if (targetClass.isArray()) { return reflectionHashCode((Object[]) obj); } if (obj instanceof Collection) { return reflectionHashCode((Collection<?>) obj); } if (obj instanceof Map) { return reflectionHashCode((Map<?, ?>) obj); } // determine whether the object's class declares hashCode() or has a // superClass other than java.lang.Object that declares hashCode() Class<?> clazz = (obj instanceof Class) ? (Class<?>) obj : obj.getClass(); Method hashCodeMethod = ReflectionUtils.findMethod(clazz, "hashCode", new Class[0]); if (hashCodeMethod != null) { return obj.hashCode(); } // could not find a hashCode other than the one declared by // java.lang.Object int hash = INITIAL_HASH; try { while (targetClass != null) { Field[] fields = targetClass.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; int modifiers = field.getModifiers(); if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) { hash = MULTIPLIER * hash + reflectionHashCode(field.get(obj)); } } targetClass = targetClass.getSuperclass(); } } catch (IllegalAccessException exception) { // ///CLOVER:OFF ReflectionUtils.handleReflectionException(exception); // ///CLOVER:ON } return hash; }
@Test public void testFeignClientType() throws IllegalAccessException { assertThat(this.feignClient, is(instanceOf(feign.ribbon.RibbonClient.class))); Field field = ReflectionUtils.findField(feign.ribbon.RibbonClient.class, "delegate", Client.class); ReflectionUtils.makeAccessible(field); Client delegate = (Client) field.get(this.feignClient); assertThat(delegate, is(instanceOf(feign.Client.Default.class))); }
private Object doInvokeMethod(Method method, Object target, Object[] args) throws Exception { ReflectionUtils.makeAccessible(method); try { return method.invoke(target, args); } catch (InvocationTargetException ex) { ReflectionUtils.rethrowException(ex.getTargetException()); } throw new IllegalStateException("Should never get here"); }
private static Object getField(Object target, String name) { if (target != null) { Field field = ReflectionUtils.findField(target.getClass(), name); if (field != null) { ReflectionUtils.makeAccessible(field); return ReflectionUtils.getField(field, target); } } return null; }
/** * Get a static field value. * * @param clazz The class to check for static property * @param name The field name * @return The value if there is one, or null if unset OR there is no such field */ public static Object getStaticFieldValue(Class<?> clazz, String name) { Field field = ReflectionUtils.findField(clazz, name); if (field != null) { ReflectionUtils.makeAccessible(field); try { return field.get(clazz); } catch (IllegalAccessException ignored) { } } return null; }
protected void init() throws ClassNotFoundException { this.proxyObjectType = ClassUtils.resolveClassName(getProxyInterfaceName(), ClassUtils.getDefaultClassLoader()); final Class<?> modelParameterClazz = ClassUtils.resolveClassName( "org.springframework.web.servlet.ModelAndView", ClassUtils.getDefaultClassLoader()); this.getModelMapMethod = ReflectionUtils.findMethod(modelParameterClazz, "getModelMap"); this.getViewNameMethod = ReflectionUtils.findMethod(modelParameterClazz, "getViewName"); this.setViewNameMethod = ReflectionUtils.findMethod(modelParameterClazz, "setViewName", String.class); }
/** * Determine if the annotated field or method requires its dependency. * * <p>A 'required' dependency means that autowiring should fail when no beans are found. * Otherwise, the autowiring process will simply bypass the field or method when no beans are * found. * * @param annotation the Autowired annotation * @return whether the annotation indicates that a dependency is required */ protected boolean determineRequiredStatus(Annotation annotation) { try { Method method = ReflectionUtils.findMethod(annotation.annotationType(), this.requiredParameterName); return (this.requiredParameterValue == (Boolean) ReflectionUtils.invokeMethod(method, annotation)); } catch (Exception ex) { // required by default return true; } }
protected PreferenceService getPreferenceService() { Field field = ReflectionUtils.findField(super.getClass(), "preferenceService"); ReflectionUtils.makeAccessible(field); try { return (PreferenceService) field.get(this); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
private Integer getLocalPort(Connector connector) { try { // Jetty 9 internals are different, but the method name is the same return (Integer) ReflectionUtils.invokeMethod( ReflectionUtils.findMethod(connector.getClass(), "getLocalPort"), connector); } catch (Exception ex) { JettyEmbeddedServletContainer.logger.info( "could not determine port ( " + ex.getMessage() + ")"); return 0; } }
public void testDefaultJarSettings() throws Exception { Properties defaultSettings = bundleCreator.getSettings(); Field field = ReflectionUtils.findField( AbstractConfigurableBundleCreatorTests.class, "jarSettings", Properties.class); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, null, defaultSettings); assertNotNull(defaultSettings); assertNotNull(bundleCreator.getRootPath()); assertNotNull(bundleCreator.getBundleContentPattern()); assertNotNull(bundleCreator.getManifestLocation()); }
static { /** * Need for full reuse {@link RequestMappingHandlerMapping}'s logic and makes this class Spring * MVC version independent. */ CREATE_REQUEST_MAPPING_INFO_METHOD = ReflectionUtils.findMethod( RequestMappingHandlerMapping.class, "createRequestMappingInfo", org.springframework.web.bind.annotation.RequestMapping.class, RequestCondition.class); ReflectionUtils.makeAccessible(CREATE_REQUEST_MAPPING_INFO_METHOD); }
private void injectValue(Field field, Object currentBean, String propName, Object propValue) { // Set as true for modifications ReflectionUtils.makeAccessible(field); // Update property ReflectionUtils.setField(field, currentBean, propValue); logger.debug( "Injection of property '" + propName + "' on " + currentBean.getClass().getName() + "." + field.getName()); }
private String getValue(Annotation[] annotations, Class<? extends Annotation> annotationClass) { for (Annotation annotation : annotations) { if (annotationClass.isInstance(annotation)) { Method valueMethod = ReflectionUtils.findMethod(annotationClass, "value"); if (valueMethod != null) { return (String) ReflectionUtils.invokeMethod(valueMethod, annotation); } else { return null; } } } return null; }
/** * utility method that generically returns a criterion using methods in Restrictions * * @param constraintName - the criteria */ protected Criterion callRestrictionsMethod( String constraintName, Class<?>[] paramTypes, Object[] params) { final Method restrictionsMethod = ReflectionUtils.findMethod(Restrictions.class, constraintName, paramTypes); Assert.notNull( restrictionsMethod, "Could not find method: " + constraintName + " in class Restrictions for parameters: " + ArrayUtils.toString(params) + " with types: " + ArrayUtils.toString(paramTypes)); return (Criterion) ReflectionUtils.invokeMethod(restrictionsMethod, null, params); }
private void configureParameterNameProviderIfPossible(Configuration configuration) { try { Class<?> parameterNameProviderClass = ClassUtils.forName("javax.validation.ParameterNameProvider", getClass().getClassLoader()); Method parameterNameProviderMethod = Configuration.class.getMethod("parameterNameProvider", parameterNameProviderClass); final Object defaultProvider = ReflectionUtils.invokeMethod( Configuration.class.getMethod("getDefaultParameterNameProvider"), configuration); final ParameterNameDiscoverer discoverer = this.parameterNameDiscoverer; Object parameterNameProvider = Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] {parameterNameProviderClass}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getParameterNames")) { String[] result = null; if (args[0] instanceof Constructor) { result = discoverer.getParameterNames((Constructor) args[0]); } else if (args[0] instanceof Method) { result = discoverer.getParameterNames((Method) args[0]); } if (result != null) { return Arrays.asList(result); } else { try { return method.invoke(defaultProvider, args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } else { // toString, equals, hashCode try { return method.invoke(this, args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } }); ReflectionUtils.invokeMethod( parameterNameProviderMethod, configuration, parameterNameProvider); } catch (Exception ex) { // Bean Validation 1.1 API not available - simply not applying the ParameterNameDiscoverer } }
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) { throw new IllegalArgumentException( "Could not find field [" + name + "] on target [" + target + "]"); } if (logger.isDebugEnabled()) { logger.debug("Getting field [" + name + "] from target [" + target + "]"); } ReflectionUtils.makeAccessible(field); return ReflectionUtils.getField(field, target); }
@SuppressWarnings("unchecked") private T getBean() { if (name != null) { return (T) beanFactory.getBean(name); } try { return type.newInstance(); } catch (InstantiationException e) { ReflectionUtils.handleReflectionException(e); } catch (IllegalAccessException e) { ReflectionUtils.handleReflectionException(e); } // should not happen throw new IllegalStateException("Internal error: could not create bean instance for mapping."); }
/** * @param testContext the current test context * @throws Exception if there is a problem * @see TestExecutionListener#beforeTestMethod(TestContext) */ @Override public void beforeTestMethod(TestContext testContext) throws Exception { Method hasAttributeMethod = TestContext.class.getMethod(HAS_ATTRIBUTE_METHOD_NAME, String.class); Boolean hasAttribute = (Boolean) ReflectionUtils.invokeMethod(hasAttributeMethod, testContext, STEP_EXECUTION); if (hasAttribute) { Method method = TestContext.class.getMethod(GET_ATTRIBUTE_METHOD_NAME, String.class); StepExecution stepExecution = (StepExecution) ReflectionUtils.invokeMethod(method, testContext, STEP_EXECUTION); StepSynchronizationManager.register(stepExecution); } }
@Override protected boolean isEligibleForOverriding(String className) { if (isExcluded(className) || ContextTypeMatchClassLoader.this.isExcluded(className)) { return false; } ReflectionUtils.makeAccessible(findLoadedClassMethod); ClassLoader parent = getParent(); while (parent != null) { if (ReflectionUtils.invokeMethod(findLoadedClassMethod, parent, className) != null) { return false; } parent = parent.getParent(); } return true; }