Example usage for java.lang.reflect Method toString

List of usage examples for java.lang.reflect Method toString

Introduction

In this page you can find the example usage for java.lang.reflect Method toString.

Prototype

public String toString() 

Source Link

Document

Returns a string describing this Method .

Usage

From source file:org.evosuite.setup.TestClusterGenerator.java

public static boolean canUse(Method m, Class<?> ownerClass) {

    if (m.isBridge()) {
        logger.debug("Excluding bridge method: {}", m.toString());
        return false;
    }// w  ww  .  jav a 2 s .  c o m

    if (m.isSynthetic()) {
        logger.debug("Excluding synthetic method: {}", m.toString());
        return false;
    }

    if (!Properties.USE_DEPRECATED && m.isAnnotationPresent(Deprecated.class)) {
        logger.debug("Excluding deprecated method {}", m.getName());
        return false;
    }

    if (m.isAnnotationPresent(Test.class)) {
        logger.debug("Excluding test method {}", m.getName());
        return false;
    }

    if (m.isAnnotationPresent(EvoSuiteExclude.class)) {
        logger.debug("Excluding method with exclusion annotation {}", m.getName());
        return false;
    }

    if (m.getDeclaringClass().equals(java.lang.Object.class)) {
        return false;
    }

    if (!m.getReturnType().equals(String.class) && !canUse(m.getReturnType())) {
        return false;
    }

    if (m.getDeclaringClass().equals(Enum.class)) {
        return false;
        /*
        if (m.getName().equals("valueOf") || m.getName().equals("values")
         || m.getName().equals("ordinal")) {
           logger.debug("Excluding valueOf for Enum " + m.toString());
           return false;
        }
        // Skip compareTo on enums (like Randoop)
        if (m.getName().equals("compareTo") && m.getParameterTypes().length == 1
         && m.getParameterTypes()[0].equals(Enum.class))
           return false;
           */
    }

    if (m.getDeclaringClass().equals(java.lang.Thread.class))
        return false;

    // Hashcode only if we need to cover it
    if (m.getName().equals("hashCode") && !m.getDeclaringClass().equals(Properties.getTargetClass()))
        return false;

    // Randoop special case: just clumps together a bunch of hashCodes, so skip it
    if (m.getName().equals("deepHashCode") && m.getDeclaringClass().equals(Arrays.class))
        return false;

    // Randoop special case: differs too much between JDK installations
    if (m.getName().equals("getAvailableLocales"))
        return false;

    if (m.getName().equals(ClassResetter.STATIC_RESET)) {
        logger.debug("Ignoring static reset class");
        return false;
    }

    if (isForbiddenNonDeterministicCall(m)) {
        return false;
    }

    if (!Properties.CONSIDER_MAIN_METHODS && m.getName().equals("main") && Modifier.isStatic(m.getModifiers())
            && Modifier.isPublic(m.getModifiers())) {
        logger.debug("Ignoring static main method ");
        return false;
    }

    /*
    if(m.getTypeParameters().length > 0) {
       logger.debug("Cannot handle generic methods at this point");
       if(m.getDeclaringClass().equals(Properties.getTargetClass())) {
    LoggingUtils.getEvoLogger().info("* Skipping method "+m.getName()+": generic methods are not handled yet");
       }
       return false;
    }
    */

    // If default or
    if (Modifier.isPublic(m.getModifiers())) {
        makeAccessible(m);
        return true;
    }

    // If default access rights, then check if this class is in the same package as the target class
    if (!Modifier.isPrivate(m.getModifiers())) {
        //              && !Modifier.isProtected(m.getModifiers())) {
        String packageName = ClassUtils.getPackageName(ownerClass);
        String declaredPackageName = ClassUtils.getPackageName(m.getDeclaringClass());
        if (packageName.equals(Properties.CLASS_PREFIX) && packageName.equals(declaredPackageName)) {
            makeAccessible(m);
            return true;
        }
    }

    return false;
}

From source file:org.jcurl.demo.tactics.old.ActionRegistry.java

public Object registerController(final Object controller) {
    final Class<?> clz = controller.getClass();
    for (final Method me : clz.getMethods()) {
        final JCAction ma = me.getAnnotation(JCAction.class);
        if (ma == null)
            continue;
        Map<Method, Action> m = i2a.get(controller);
        if (m == null) {
            i2a.put(controller, m = new HashMap<Method, Action>());
            if (c2a.put(clz, m) != null)
                throw new IllegalStateException(clz.getName());
        }/*  w w w  .ja  v  a2  s .  c o m*/
        if (m.put(me, createAction(controller, me, ma)) != null)
            throw new IllegalStateException(me.toString());
    }
    return controller;
}

From source file:org.flite.cach3.aop.UpdateAssignCacheAdvice.java

@AfterReturning(pointcut = "updateAssign()", returning = "retVal")
public Object cacheUpdateAssign(final JoinPoint jp, final Object retVal) throws Throwable {
    // If we've disabled the caching programmatically (or via properties file) just flow through.
    if (isCacheDisabled()) {
        LOG.debug("Caching is disabled.");
        return retVal;
    }/*from ww w.j  ava  2s .c om*/

    final MemcachedClientIF cache = getMemcachedClient();
    // This is injected caching.  If anything goes wrong in the caching, LOG the crap outta it,
    // but do not let it surface up past the AOP injection itself.
    try {
        final Method methodToCache = getMethodToCache(jp);
        final UpdateAssignCache annotation = methodToCache.getAnnotation(UpdateAssignCache.class);
        final AnnotationInfo info = getAnnotationInfo(annotation, methodToCache.getName(), getJitterDefault());
        final String cacheKey = buildCacheKey(info.getAsString(AType.ASSIGN_KEY),
                info.getAsString(AType.NAMESPACE), info.getAsString(AType.KEY_PREFIX));
        final int dataIndex = info.getAsInteger(AType.DATA_INDEX, -2).intValue();
        final Object dataObject = dataIndex == -1 ? retVal
                : getIndexObject(dataIndex, jp.getArgs(), methodToCache.toString());
        final Object submission = (dataObject == null) ? new PertinentNegativeNull() : dataObject;
        boolean cacheable = true;
        if (submission instanceof CacheConditionally) {
            cacheable = ((CacheConditionally) submission).isCacheable();
        }
        if (cacheable) {
            cache.set(cacheKey, info.getAsInteger(AType.JITTER), submission);
        }

        // Notify the observers that a cache interaction happened.
        final List<UpdateAssignCacheListener> listeners = getPertinentListeners(UpdateAssignCacheListener.class,
                info.getAsString(AType.NAMESPACE));
        if (listeners != null && !listeners.isEmpty()) {
            for (final UpdateAssignCacheListener listener : listeners) {
                try {
                    listener.triggeredUpdateAssignCache(info.getAsString(AType.NAMESPACE),
                            info.getAsString(AType.ASSIGN_KEY), dataObject, retVal, jp.getArgs());
                } catch (Exception ex) {
                    LOG.warn("Problem when triggering a listener.", ex);
                }
            }
        }
    } catch (Exception ex) {
        if (LOG.isDebugEnabled()) {
            LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error.", ex);
        } else {
            LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error: " + ex.getMessage());
        }
    }

    return retVal;
}

From source file:org.paxle.core.impl.Activator.java

/**
 * @see {@link org.eclipse.osgi.service.runnable.ParameterizedRunnable#run(Object)}
 * @see {@link org.eclipse.osgi.service.runnable.ApplicationRunnable#stop()}
 *//*from   ww  w .  j a va  2 s .  c o  m*/
public synchronized Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.getName().equals("run")) {
        // wait until we need to shutdown
        this.wait();

        // return exit code
        return Integer.valueOf(0);
    } else if (method.getName().equals("stop")) {
        // signal equinox to shutdown
        System.setProperty("osgi.noShutdown", "false");

        // wakeup main thread
        this.notifyAll();

        // return void
        return null;
    } else {
        throw new IllegalArgumentException(String.format("Unknown function call %s", method.toString()));
    }
}

From source file:com.kixeye.chassis.transport.websocket.WebSocketMessageMappingRegistry.java

@PostConstruct
public void registerWebSocketActions() throws BeansException {
    String[] controllerBeanNames = beanFactory.getBeanNamesForAnnotation(WebSocketController.class);

    if (controllerBeanNames != null && controllerBeanNames.length > 0) {
        try {//from   w  ww.  j  a  v  a  2  s  . co m
            for (String beanName : controllerBeanNames) {
                BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);

                Class<?> beanClass = Class.forName(beanDef.getBeanClassName());

                for (Method method : beanClass.getMethods()) {
                    ActionMapping mapping = method.getAnnotation(ActionMapping.class);

                    if (mapping != null) {
                        if (mapping.value() != null && mapping.value().length > 0) {
                            Map<String, String> requirements = new HashMap<>();

                            if (mapping.propertyRequirements() != null) {
                                for (ActionPropertyRequirement requirement : mapping.propertyRequirements()) {
                                    requirements.put(requirement.name(), requirement.value());
                                }
                            }

                            for (String action : mapping.value()) {
                                logger.info("Registering destination [{}] with handler [{}].", action,
                                        method.toString());

                                Map<String, WebSocketActionArgumentResolver> argumentResolverBeans = beanFactory
                                        .getBeansOfType(WebSocketActionArgumentResolver.class);

                                if (argumentResolverBeans != null && !argumentResolverBeans.isEmpty()) {
                                    logger.info(
                                            "Registering WebSocketActionArgumentResolver beans {} with action {}",
                                            Joiner.on(",").join(argumentResolverBeans.keySet(), action));
                                }

                                actions.put(action, new WebSocketAction(method, requirements,
                                        argumentResolverBeans == null ? null
                                                : argumentResolverBeans.values().toArray(
                                                        new WebSocketActionArgumentResolver[argumentResolverBeans
                                                                .size()])));
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new FatalBeanException("Unable to configure bean", e);
        }
    } else {
        logger.warn("No WebSocketController beans defined.");
    }
}

From source file:ca.uhn.fhir.rest.method.OperationParameter.java

@SuppressWarnings("unchecked")
@Override/*from  w  ww  .  ja v a 2s.co m*/
public void initializeTypes(Method theMethod, Class<? extends Collection<?>> theOuterCollectionType,
        Class<? extends Collection<?>> theInnerCollectionType, Class<?> theParameterType) {
    if (getContext().getVersion().getVersion().isRi()) {
        if (IDatatype.class.isAssignableFrom(theParameterType)) {
            throw new ConfigurationException("Incorrect use of type " + theParameterType.getSimpleName()
                    + " as parameter type for method when context is for version "
                    + getContext().getVersion().getVersion().name() + " in method: " + theMethod.toString());
        }
    }

    myParameterType = theParameterType;
    if (theInnerCollectionType != null) {
        myInnerCollectionType = CollectionBinder.getInstantiableCollectionType(theInnerCollectionType, myName);
        if (myMax == OperationParam.MAX_DEFAULT) {
            myMax = OperationParam.MAX_UNLIMITED;
        }
    } else if (IQueryParameterAnd.class.isAssignableFrom(myParameterType)) {
        if (myMax == OperationParam.MAX_DEFAULT) {
            myMax = OperationParam.MAX_UNLIMITED;
        }
    } else {
        if (myMax == OperationParam.MAX_DEFAULT) {
            myMax = 1;
        }
    }

    boolean typeIsConcrete = !myParameterType.isInterface()
            && !Modifier.isAbstract(myParameterType.getModifiers());

    //@formatter:off
    boolean isSearchParam = IQueryParameterType.class.isAssignableFrom(myParameterType)
            || IQueryParameterOr.class.isAssignableFrom(myParameterType)
            || IQueryParameterAnd.class.isAssignableFrom(myParameterType);
    //@formatter:off

    /*
     * Note: We say here !IBase.class.isAssignableFrom because a bunch of DSTU1/2 datatypes also
     * extend this interface. I'm not sure if they should in the end.. but they do, so we
     * exclude them.
     */
    isSearchParam &= typeIsConcrete && !IBase.class.isAssignableFrom(myParameterType);

    myAllowGet = IPrimitiveType.class.isAssignableFrom(myParameterType) || String.class.equals(myParameterType)
            || isSearchParam || ValidationModeEnum.class.equals(myParameterType);

    /*
     * The parameter can be of type string for validation methods - This is a bit weird. See ValidateDstu2Test. We
     * should probably clean this up..
     */
    if (!myParameterType.equals(IBase.class) && !myParameterType.equals(String.class)) {
        if (IBaseResource.class.isAssignableFrom(myParameterType) && myParameterType.isInterface()) {
            myParamType = "Resource";
        } else if (DateRangeParam.class.isAssignableFrom(myParameterType)) {
            myParamType = "date";
            myMax = 2;
            myAllowGet = true;
        } else if (myParameterType.equals(ValidationModeEnum.class)) {
            myParamType = "code";
        } else if (IBase.class.isAssignableFrom(myParameterType) && typeIsConcrete) {
            myParamType = myContext.getElementDefinition((Class<? extends IBase>) myParameterType).getName();
        } else if (isSearchParam) {
            myParamType = "string";
            mySearchParameterBinding = new SearchParameter(myName, myMin > 0);
            mySearchParameterBinding.setCompositeTypes(COMPOSITE_TYPES);
            mySearchParameterBinding.setType(myContext, theParameterType, theInnerCollectionType,
                    theOuterCollectionType);
            myConverter = new OperationParamConverter();
        } else {
            throw new ConfigurationException("Invalid type for @OperationParam: " + myParameterType.getName());
        }

    }

}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * @return the {@link String} presentation of given {@link Method}. If this {@link Method} is
 *         declared in some "enchanced" {@link Class}, and there was same {@link Method} in
 *         "normal" {@link Class}, then <code>toString</code> of "normal" {@link Method} returned.
 *//* w ww . jav a 2  s .co m*/
public static String toString(Method method) {
    String methodSignature = getMethodSignature(method);
    // try to find in "normal" Class method with same signature
    while (isEnchancedClass(method.getDeclaringClass())) {
        Class<?> superClass = method.getDeclaringClass().getSuperclass();
        Method superMethod = getMethodBySignature(superClass, methodSignature);
        if (superMethod == null) {
            break;
        }
        method = superMethod;
    }
    // OK, use toString()
    return method.toString();
}

From source file:xbird.xquery.func.ext.JavaFunction.java

@Override
public JavaFunction staticAnalysis(StaticContext context, List<? extends XQExpression> params)
        throws XQueryException {
    QualifiedName qname = getName();/*from ww  w .  ja va2  s .co m*/
    String clazz = toCamelCase(qname.getNamespaceURI().substring(5));
    String methodname = qname.getLocalPart();

    Class[] types = getArgTypes(params);
    final Method m;
    try {
        Class primeClass = Class.forName(clazz);
        assert (primeClass != null);
        m = PrivilegedAccessor.getMethod(primeClass, methodname, types);
    } catch (Exception e) {
        final StringBuilder msg = new StringBuilder();
        msg.append("method not found: " + clazz + '#' + methodname + '(');
        for (int i = 0; i < types.length; i++) {
            if (i != 0) {
                msg.append(',');
            }
            msg.append(types[i].getSimpleName());
        }
        msg.append(')');
        throw new XQueryException(msg.toString(), e);
    }
    if (Modifier.isStatic(m.getModifiers()) == false) {
        throw new XQueryException("Method '" + m.getName() + "' is not a static method.");
    }
    m.setAccessible(true);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Found Java method: " + m.toString());
    }
    // TODO return type setting.
    Class retType = m.getReturnType();

    this.bindedMethod = m;
    return this;
}

From source file:org.flite.cach3.aop.InvalidateMultiCacheAdvice.java

private void doInvalidate(final JoinPoint jp, final Object retVal) throws Throwable {
    if (isCacheDisabled()) {
        LOG.debug("Caching is disabled.");
        return;/*from   w  w  w  .  jav a  2  s .  com*/
    }

    final MemcachedClientIF cache = getMemcachedClient();
    final Method methodToCache = getMethodToCache(jp);

    List<InvalidateMultiCache> lAnnotations;

    if (methodToCache.getAnnotation(InvalidateMultiCache.class) != null) {
        lAnnotations = Arrays.asList(methodToCache.getAnnotation(InvalidateMultiCache.class));
    } else {
        lAnnotations = Arrays.asList(methodToCache.getAnnotation(InvalidateMultiCaches.class).value());
    }

    for (int i = 0; i < lAnnotations.size(); i++) {
        // This is injected caching.  If anything goes wrong in the caching, LOG the crap outta it,
        // but do not let it surface up past the AOP injection itself.
        try {
            final AnnotationInfo info = getAnnotationInfo(lAnnotations.get(i), methodToCache.getName());
            final List<Object> keyObjects = (List<Object>) getIndexObject(info.getAsInteger(AType.KEY_INDEX),
                    retVal, jp.getArgs(), methodToCache.toString());
            final List<String> baseKeys = UpdateMultiCacheAdvice.getBaseKeys(keyObjects,
                    info.getAsString(AType.KEY_TEMPLATE), retVal, jp.getArgs(), factory, methodStore);
            for (final String base : baseKeys) {
                final String cacheKey = buildCacheKey(base, info.getAsString(AType.NAMESPACE),
                        info.getAsString(AType.KEY_PREFIX));
                cache.delete(cacheKey);
            }

            // Notify the observers that a cache interaction happened.
            final List<InvalidateMultiCacheListener> listeners = getPertinentListeners(
                    InvalidateMultiCacheListener.class, info.getAsString(AType.NAMESPACE));
            if (listeners != null && !listeners.isEmpty()) {
                for (final InvalidateMultiCacheListener listener : listeners) {
                    try {
                        listener.triggeredInvalidateMultiCache(info.getAsString(AType.NAMESPACE),
                                info.getAsString(AType.KEY_PREFIX, null), baseKeys, retVal, jp.getArgs());
                    } catch (Exception ex) {
                        LOG.warn("Problem when triggering a listener.", ex);
                    }
                }
            }
        } catch (Throwable ex) {
            if (LOG.isDebugEnabled()) {
                LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error.", ex);
            } else {
                LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error: " + ex.getMessage());
            }
        }
    }

}

From source file:org.eclipse.wb.internal.rcp.model.rcp.ViewPartInfo.java

/**
 * Initializes this {@link ViewPart} with {@link IViewSite}.
 *//*from   w w  w  .  ja  v a  2s. co  m*/
@Override
protected void applyActionBars() throws Exception {
    ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this);
    Class<?> viewSiteClass = editorLoader.loadClass("org.eclipse.ui.IViewSite");
    // create IViewSite
    Object viewSite = Proxy.newProxyInstance(editorLoader, new Class<?>[] { viewSiteClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String signature = ReflectionUtils.getMethodSignature(method);
                    if (signature.equals("toString()")) {
                        return "IViewSite_stub";
                    }
                    if (signature.equals("hashCode()")) {
                        return 0;
                    }
                    if (signature.equals("getActionBars()")) {
                        return m_actionBars;
                    }
                    if (signature.equals("getId()")) {
                        return getID();
                    }
                    if (signature.equals("getSecondaryId()")) {
                        return null;
                    }
                    if (signature.equals("getWorkbenchWindow()")) {
                        return DesignerPlugin.getActiveWorkbenchWindow();
                    }
                    throw new NotImplementedException(method.toString());
                }
            });
    // call init(IViewSite)
    ReflectionUtils.invokeMethod(getObject(), "init(org.eclipse.ui.IViewSite)", viewSite);
}