Example usage for org.springframework.util ReflectionUtils findMethod

List of usage examples for org.springframework.util ReflectionUtils findMethod

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils findMethod.

Prototype

@Nullable
public static Method findMethod(Class<?> clazz, String name) 

Source Link

Document

Attempt to find a Method on the supplied class with the supplied name and no parameters.

Usage

From source file:org.springframework.cloud.netflix.feign.support.SpringMvcContractTests.java

/**
 * For abstract (e.g. interface) methods, only Java 8 Parameter names (compiler arg
 * -parameters) can supply parameter names; bytecode-based strategies use local
 * variable declarations, of which there are none for abstract methods.
 * @param m//from   w  w  w .  ja v  a 2  s  . c  om
 * @return whether a parameter name was found
 * @throws IllegalArgumentException if method has no parameters
 */
private static boolean hasJava8ParameterNames(Method m) {
    org.springframework.util.Assert.isTrue(m.getParameterTypes().length > 0, "method has no parameters");
    if (EXECUTABLE_TYPE != null) {
        Method getParameters = ReflectionUtils.findMethod(EXECUTABLE_TYPE, "getParameters");
        try {
            Object[] parameters = (Object[]) getParameters.invoke(m);
            Method isNamePresent = ReflectionUtils.findMethod(parameters[0].getClass(), "isNamePresent");
            return Boolean.TRUE.equals(isNamePresent.invoke(parameters[0]));
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
        }
    }
    return false;
}

From source file:org.springframework.data.hadoop.test.support.compat.MiniMRClusterCompat.java

/**
 * Finds and calls lifecycle stop method for
 * given cluster via reflection.//from w  w w .  j  a v a  2 s .co  m
 *
 * @param mrClusterObject the Cluster Object
 */
public static void stopCluster(Object mrClusterObject) {
    Assert.notNull(mrClusterObject, "mrClusterObject must not be null");
    log.info("Stopping cluster=" + mrClusterObject);

    Method method = ReflectionUtils.findMethod(mrClusterObject.getClass(), "stop");
    if (method == null) {
        method = ReflectionUtils.findMethod(mrClusterObject.getClass(), "shutdown");
    }

    if (method != null) {
        ReflectionUtils.invokeMethod(method, mrClusterObject);
    } else {
        log.warn("Can't find stop/shutdown method for cluster=" + mrClusterObject);
    }
}

From source file:org.springframework.data.hadoop.test.support.compat.MiniMRClusterCompat.java

/**
 * Gets the {@link Configuration} from a cluster.
 *
 * @param mrClusterObject the Cluster Object
 * @return the cluster {@link Configuration}
 *///from w w w.j ava 2  s  .  c  om
public static Configuration getConfiguration(Object mrClusterObject) {
    Assert.notNull(mrClusterObject, "mrClusterObject must not be null");
    log.info("Getting configuration for cluster=" + mrClusterObject);

    Method method = ReflectionUtils.findMethod(mrClusterObject.getClass(), "getConfig");
    if (method == null) {
        method = ReflectionUtils.findMethod(mrClusterObject.getClass(), "createJobConf");
    }

    if (method != null) {
        return (Configuration) ReflectionUtils.invokeMethod(method, mrClusterObject);
    } else {
        log.warn("Can't find configuration for cluster=" + mrClusterObject);
    }

    return null;
}

From source file:org.springframework.data.solr.server.support.SolrClientUtils.java

/**
 * Close the {@link SolrClient} by calling {@link SolrClient#close()} or {@code shutdown} for the generation 5
 * libraries./*  w  w w  . ja  v  a2s  . co m*/
 *
 * @param solrClient must not be {@literal null}.
 * @throws DataAccessResourceFailureException
 * @since 2.1
 */
public static void close(SolrClient solrClient) {

    Assert.notNull(solrClient, "SolrClient must not be null!");

    try {
        if (solrClient instanceof Closeable) {
            solrClient.close();
        } else {
            Method shutdownMethod = ReflectionUtils.findMethod(solrClient.getClass(), "shutdown");
            if (shutdownMethod != null) {
                shutdownMethod.invoke(solrClient);
            }
        }
    } catch (Exception e) {
        throw new DataAccessResourceFailureException("Cannot close SolrClient", e);
    }
}

From source file:org.springframework.faces.model.SelectionTrackingActionListener.java

private void trackSelection(UIComponent component) {
    // Find parent component with a SelectionAware model if it exists
    UIComponent currentComponent = component;
    while (currentComponent.getParent() != null && !(currentComponent.getParent() instanceof UIViewRoot)) {
        UIComponent parent = currentComponent.getParent();
        Method valueAccessor = ReflectionUtils.findMethod(parent.getClass(), "getValue");
        if (valueAccessor != null) {
            Object value = ReflectionUtils.invokeMethod(valueAccessor, parent);
            if (value != null && value instanceof SelectionAware) {
                ((SelectionAware<?>) value).setCurrentRowSelected(true);
                if (logger.isDebugEnabled()) {
                    logger.debug("Row selection has been set on the current SelectionAware data model.");
                }//w w  w  .  j  av  a  2  s. c  om
                break;
            }
        }
        currentComponent = currentComponent.getParent();
    }
}

From source file:org.springframework.flex.core.MessageBrokerFactoryBean.java

private void initThreadLocals() {
    // allocate static thread local objects

    // If available, invoke the MessageBroker.createThreadLocalObjects() method:
    Method createThreadLocalObjMethod = ReflectionUtils.findMethod(MessageBroker.class,
            "createThreadLocalObjects");
    if (createThreadLocalObjMethod != null) {
        ReflectionUtils.invokeMethod(createThreadLocalObjMethod, null);
    }//from  w  w w . j  av  a 2  s.  c  o  m

    FlexContext.createThreadLocalObjects();
    SerializationContext.createThreadLocalObjects();
    TypeMarshallingContext.createThreadLocalObjects();
    PropertyProxyRegistry.getRegistry();
}

From source file:org.springframework.flex.core.MessageBrokerFactoryBean.java

private void destroyThreadLocals() {
    // clear static member variables for shutdown
    MBeanServerLocatorFactory.clear();/*  ww w.j  a v a  2s .  c o m*/

    // If available, invoke the MessageBroker.releaseThreadLocalObjects() method:
    Method releaseThreadLocalObjMethod = ReflectionUtils.findMethod(MessageBroker.class,
            "releaseThreadLocalObjects");
    if (releaseThreadLocalObjMethod != null) {
        ReflectionUtils.invokeMethod(releaseThreadLocalObjMethod, null);
    }

    FlexContext.releaseThreadLocalObjects();
    SerializationContext.releaseThreadLocalObjects();
    TypeMarshallingContext.releaseThreadLocalObjects();
}

From source file:org.springframework.integration.channel.DirectChannelTests.java

@Test //  See INT-2434
public void testChannelCreationWithBeanDefinitionOverrideTrue() throws Exception {
    ClassPathXmlApplicationContext parentContext = new ClassPathXmlApplicationContext("parent-config.xml",
            this.getClass());
    MessageChannel parentChannelA = parentContext.getBean("parentChannelA", MessageChannel.class);
    MessageChannel parentChannelB = parentContext.getBean("parentChannelB", MessageChannel.class);

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
    context.setAllowBeanDefinitionOverriding(false);
    context.setConfigLocations(/*from ww  w  .  j av a2s  . co m*/
            new String[] { "classpath:org/springframework/integration/channel/channel-override-config.xml" });
    context.setParent(parentContext);
    Method method = ReflectionUtils.findMethod(ClassPathXmlApplicationContext.class, "obtainFreshBeanFactory");
    method.setAccessible(true);
    method.invoke(context);
    assertFalse(context.containsBean("channelA"));
    assertFalse(context.containsBean("channelB"));
    assertTrue(context.containsBean("channelC"));
    assertTrue(context.containsBean("channelD"));

    context.refresh();

    PublishSubscribeChannel channelEarly = context.getBean("channelEarly", PublishSubscribeChannel.class);

    assertTrue(context.containsBean("channelA"));
    assertTrue(context.containsBean("channelB"));
    assertTrue(context.containsBean("channelC"));
    assertTrue(context.containsBean("channelD"));
    EventDrivenConsumer consumerA = context.getBean("serviceA", EventDrivenConsumer.class);
    assertEquals(context.getBean("channelA"), TestUtils.getPropertyValue(consumerA, "inputChannel"));
    assertEquals(context.getBean("channelB"), TestUtils.getPropertyValue(consumerA, "handler.outputChannel"));

    EventDrivenConsumer consumerB = context.getBean("serviceB", EventDrivenConsumer.class);
    assertEquals(context.getBean("channelB"), TestUtils.getPropertyValue(consumerB, "inputChannel"));
    assertEquals(context.getBean("channelC"), TestUtils.getPropertyValue(consumerB, "handler.outputChannel"));

    EventDrivenConsumer consumerC = context.getBean("serviceC", EventDrivenConsumer.class);
    assertEquals(context.getBean("channelC"), TestUtils.getPropertyValue(consumerC, "inputChannel"));
    assertEquals(context.getBean("channelD"), TestUtils.getPropertyValue(consumerC, "handler.outputChannel"));

    EventDrivenConsumer consumerD = context.getBean("serviceD", EventDrivenConsumer.class);
    assertEquals(parentChannelA, TestUtils.getPropertyValue(consumerD, "inputChannel"));
    assertEquals(parentChannelB, TestUtils.getPropertyValue(consumerD, "handler.outputChannel"));

    EventDrivenConsumer consumerE = context.getBean("serviceE", EventDrivenConsumer.class);
    assertEquals(parentChannelB, TestUtils.getPropertyValue(consumerE, "inputChannel"));

    EventDrivenConsumer consumerF = context.getBean("serviceF", EventDrivenConsumer.class);
    assertEquals(channelEarly, TestUtils.getPropertyValue(consumerF, "inputChannel"));
}

From source file:org.springframework.test.util.ReflectionTestUtils.java

/**
 * Invoke the getter method with the given {@code name} on the supplied
 * target object with the supplied {@code value}.
 * <p>This method traverses the class hierarchy in search of the desired
 * method. In addition, an attempt will be made to make non-{@code public}
 * methods <em>accessible</em>, thus allowing one to invoke {@code protected},
 * {@code private}, and <em>package-private</em> getter methods.
 * <p>In addition, this method supports JavaBean-style <em>property</em>
 * names. For example, if you wish to get the {@code name} property on the
 * target object, you may pass either &quot;name&quot; or
 * &quot;getName&quot; as the method name.
 * @param target the target object on which to invoke the specified getter
 * method//from  www.ja  v  a 2 s .  c om
 * @param name the name of the getter method to invoke or the corresponding
 * property name
 * @return the value returned from the invocation
 * @see ReflectionUtils#findMethod(Class, String, Class[])
 * @see ReflectionUtils#makeAccessible(Method)
 * @see ReflectionUtils#invokeMethod(Method, Object, Object[])
 */
@Nullable
public static Object invokeGetterMethod(Object target, String name) {
    Assert.notNull(target, "Target object must not be null");
    Assert.hasText(name, "Method name must not be empty");

    String getterMethodName = name;
    if (!name.startsWith(GETTER_PREFIX)) {
        getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
    }
    Method method = ReflectionUtils.findMethod(target.getClass(), getterMethodName);
    if (method == null && !getterMethodName.equals(name)) {
        getterMethodName = name;
        method = ReflectionUtils.findMethod(target.getClass(), getterMethodName);
    }
    if (method == null) {
        throw new IllegalArgumentException(String.format("Could not find getter method '%s' on %s",
                getterMethodName, safeToString(target)));
    }

    if (logger.isDebugEnabled()) {
        logger.debug(
                String.format("Invoking getter method '%s' on %s", getterMethodName, safeToString(target)));
    }
    ReflectionUtils.makeAccessible(method);
    return ReflectionUtils.invokeMethod(method, target);
}

From source file:org.springframework.web.socket.server.endpoint.EndpointExporter.java

protected ServerContainer getServerContainer() {
    if (isServletApiPresent) {
        try {/*from   w w  w .  j ava2 s.  com*/
            Method getter = ReflectionUtils.findMethod(this.applicationContext.getClass(), "getServletContext");
            Object servletContext = getter.invoke(this.applicationContext);

            Method attrMethod = ReflectionUtils.findMethod(servletContext.getClass(), "getAttribute",
                    String.class);
            return (ServerContainer) attrMethod.invoke(servletContext,
                    "javax.websocket.server.ServerContainer");
        } catch (Exception ex) {
            throw new IllegalStateException(
                    "Failed to get javax.websocket.server.ServerContainer via ServletContext attribute", ex);
        }
    }
    return null;
}