Example usage for java.lang.reflect Method getGenericParameterTypes

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

Introduction

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

Prototype

@Override
public Type[] getGenericParameterTypes() 

Source Link

Usage

From source file:jef.tools.reflect.ClassEx.java

/**
 * ??//from  ww w  . j  a  v  a  2  s . c o m
 * 
 * @param method
 * @param index
 * @return
 */
public Type getMethodParamType(Method method, int index) {
    ClassEx cw = this;
    method = getRealMethod(method);
    if (method.getDeclaringClass() != this.cls) {
        Type type = GenericUtils.getSuperType(null, cls, method.getDeclaringClass());
        cw = new ClassEx(type);
    }
    Type[] types = method.getGenericParameterTypes();
    if (index < 0 || index > types.length) {
        throw new IllegalArgumentException(StringUtils.concat("the method ", method.getName(), " has ",
                String.valueOf(types.length), " params, index=", String.valueOf(index), " is out of bound."));
    }
    return BeanUtils.getBoundType(types[index], cw);
}

From source file:play.modules.swagger.PlayReader.java

private Type getParamType(Class<?> cls, Method method, String simpleTypeName, int position) {

    try {/*w w  w  . j  av a2s. c o  m*/
        Type type = getOptionTypeFromString(simpleTypeName, cls);
        if (type != null)
            return type;

        Type[] genericParameterTypes = method.getGenericParameterTypes();
        return Json.mapper().getTypeFactory().constructType(genericParameterTypes[position], cls);
    } catch (Exception e) {
        Logger.error(String.format("Exception getting parameter type for method %s, param %s at position %d"),
                e);
        return null;
    }

}

From source file:com.taobao.rpc.doclet.RPCAPIInfoHelper.java

public static RPCAPIInfo getAPIInfo(String realPath, Method method) {
    RPCAPIInfo apiInfo = new RPCAPIInfo();

    ClassInfo classInfo = RPCAPIDocletUtil.getClassInfo(method.getDeclaringClass().getName());
    MethodInfo methodInfo = null;/*from  w  w w  .j  av a2s .co  m*/

    if (classInfo != null) {
        methodInfo = classInfo.getMethodInfo(method.getName());
    }

    if (methodInfo != null) {

        apiInfo.setComment(methodInfo.getComment());
    }

    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    Security securityAnnotation = method.getAnnotation(Security.class);
    ResourceMapping resourceMapping = method.getAnnotation(ResourceMapping.class);

    Object returnType = null;

    returnType = buildTypeStructure(method.getReturnType(), method.getGenericReturnType(), null);

    boolean checkCSRF = false;
    if (securityAnnotation != null) {
        checkCSRF = securityAnnotation.checkCSRF();
    }

    apiInfo.setPattern(realPath.replaceAll("///", "/"));
    apiInfo.setCheckCSRF(checkCSRF);
    apiInfo.setResponseMimes(StringUtils.arrayToDelimitedString(resourceMapping.produces(), ","));
    apiInfo.setHttpMethod(StringUtils.arrayToDelimitedString(resourceMapping.method(), ","));

    List<RPCAPIInfo.Parameter> parameters = new ArrayList<RPCAPIInfo.Parameter>();

    RPCAPIInfo.Parameter parameter = null;
    LocalVariableTableParameterNameDiscoverer nameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
    String[] paramNames = nameDiscoverer.getParameterNames(method);
    int i = 0;

    Class<?>[] parameterTypes = method.getParameterTypes();

    Type[] genericParameterTypes = method.getGenericParameterTypes();

    Class<?> paramType = null;

    Type genericType;

    for (int k = 0; k < parameterTypes.length; k++) {

        paramType = parameterTypes[k];
        genericType = genericParameterTypes[k];

        Annotation[] pAnnotations = parameterAnnotations[i];

        if (HttpServletRequest.class.isAssignableFrom(paramType)
                || HttpServletResponse.class.isAssignableFrom(paramType)
                || ErrorContext.class.isAssignableFrom(paramType)) {
            continue;
        } // end if

        String realParamName = paramNames[k];

        if (pAnnotations.length == 0) {

            parameter = apiInfo.new Parameter();
            parameter.setName(realParamName);
            parameter.setType(buildTypeStructure(paramType, genericType, null));
            parameters.add(parameter);

            setParameterComment(parameter, realParamName, methodInfo);

            continue;
        } // end if

        for (Annotation annotation : pAnnotations) {
            parameter = apiInfo.new Parameter();
            setParameterComment(parameter, realParamName, methodInfo);

            if (annotation instanceof RequestParam) {
                RequestParam requestParam = (RequestParam) annotation;
                parameter.setName(requestParam.name());
                parameter.setType(buildTypeStructure(paramType, genericType, null));
                if (!StringUtil.isBlank(requestParam.defaultValue())) {
                    parameter.setDefaultValue(requestParam.defaultValue().trim());
                }
                parameters.add(parameter);
            } else if (annotation instanceof PathParam) {
                PathParam pathParam = (PathParam) annotation;
                parameter.setName(pathParam.name());
                parameter.setType(buildTypeStructure(paramType, genericType, null));
                if (!StringUtil.isBlank(pathParam.defaultValue())) {
                    parameter.setDefaultValue(pathParam.defaultValue().trim());
                }
                parameters.add(parameter);
            } else if (annotation instanceof JsonParam) {
                JsonParam pathParam = (JsonParam) annotation;
                parameter.setName(pathParam.value());
                parameter.setType(buildTypeStructure(paramType, genericType, null));
                parameters.add(parameter);
            } else if (annotation instanceof RequestParams) {
                parameter.setName(realParamName);
                parameter.setType(buildTypeStructure(paramType, genericType, null));
                parameters.add(parameter);
            } else if (annotation instanceof File) {
                File file = (File) annotation;
                parameter.setName(file.value());
                parameter.setType("");
                parameters.add(parameter);
            } // end if
        } // end for
        i++;
    } // end for
    apiInfo.setParmeters(parameters);
    apiInfo.setReturnType(returnType);
    return apiInfo;
}

From source file:org.op4j.devutils.selected.ImplFile.java

public void computeMethodImplementations(final ImplType implType, final Class<?> interfaceClass)
        throws Exception {

    final List<Method> interfaceMethods = new ArrayList<Method>();
    interfaceMethods.addAll(Arrays.asList(interfaceClass.getDeclaredMethods()));

    final Set<Type> extendedInterfaces = new HashSet<Type>(
            Arrays.asList(interfaceClass.getGenericInterfaces()));
    Type getReturnType = null;//  w  w  w  .j  a va 2s . c  o  m
    for (final Type extendedInterface : extendedInterfaces) {
        if (extendedInterface instanceof ParameterizedType) {
            final ParameterizedType pType = (ParameterizedType) extendedInterface;
            if (((Class<?>) pType.getRawType()).equals(UniqOperator.class)) {
                getReturnType = pType.getActualTypeArguments()[0];
            }
        }
    }

    try {
        interfaceMethods.add(UniqOpOperator.class.getMethod("get"));
    } catch (NoSuchMethodException e) {
        // nothing to do
    }

    if (this.className.contains("Array")) {
        this.element = "T[]";
    } else if (this.className.contains("List")) {
        this.element = "List<T>";
    } else if (this.className.contains("Set")) {
        this.element = "Set<T>";
    } else if (this.className.contains("Map")) {
        this.element = "Map<K,V>";
    } else {
        this.element = "T";
    }

    for (final Method interfaceMethod : interfaceMethods) {

        final String methodName = interfaceMethod.getName();
        this.methodNames.add(methodName);

        final Type[] parameterTypes = interfaceMethod.getGenericParameterTypes();

        if (methodName.startsWith("exec")) {
            this.currentLevelType = (new TypeRep(
                    ((WildcardType) ((ParameterizedType) parameterTypes[0]).getActualTypeArguments()[0])
                            .getLowerBounds()[0])).getStringRep();
            if (this.currentLevelType.endsWith("[]")) {
                this.currentLevelElement = this.currentLevelType.substring(0,
                        this.currentLevelType.length() - 2);
            } else if (this.currentLevelType.startsWith("List<") && this.currentLevelType.endsWith(">")) {
                this.currentLevelElement = this.currentLevelType.substring(5,
                        this.currentLevelType.length() - 1);
            } else if (this.currentLevelType.startsWith("Set<") && this.currentLevelType.endsWith(">")) {
                this.currentLevelElement = this.currentLevelType.substring(4,
                        this.currentLevelType.length() - 1);
            } else if (this.currentLevelType.startsWith("Map<") && this.currentLevelType.endsWith(">")) {
                this.currentLevelElement = "Map.Entry<"
                        + this.currentLevelType.substring(4, this.currentLevelType.length() - 1) + ">";
            } else {
                this.currentLevelElement = "%%CURRENTELEMENTSHOULDNOTBEHERE%%";
            }
        }

        final String returnTypeStr = (methodName.equals("get")
                ? (implType == ImplType.OP ? this.element : "Function<I," + this.element + ">")
                : (methodName.equals("getAsArrayOf")
                        ? (implType == ImplType.OP ? this.element + "[]" : "Function<I," + this.element + "[]>")
                        : (methodName.equals("getAsList")
                                ? (implType == ImplType.OP ? "List<" + this.element + ">"
                                        : "Function<I,List<" + this.element + ">>")
                                : new TypeRep(interfaceMethod.getGenericReturnType()).getStringRep()
                                        .replaceAll("ILevel", "Level"))));

        final StringBuilder parameterStrBuilder = new StringBuilder();
        parameterStrBuilder.append("(");

        List<String> normalisedParamTypes = new ArrayList<String>();
        List<String> normalisedRawParamTypes = new ArrayList<String>();
        for (int j = 0; j < parameterTypes.length; j++) {
            normalisedParamTypes.add(getNormalisedParamType(parameterTypes[j], methodName, j));
            normalisedRawParamTypes.add(
                    StringUtils.substringBefore(getNormalisedParamType(parameterTypes[j], methodName, j), "<"));
        }

        String[] paramNamesForMethod = paramNames
                .get(methodName + "%" + StringUtils.join(normalisedRawParamTypes, ","));
        if (paramNamesForMethod == null) {
            paramNamesForMethod = paramNames.get(methodName + "%" + parameterTypes.length);
            if (paramNamesForMethod == null) {
                paramNamesForMethod = paramNames.get(methodName);
            }
        }

        for (int j = 0; j < normalisedParamTypes.size(); j++) {

            if (j > 0) {
                parameterStrBuilder.append(", ");
            }

            parameterStrBuilder.append("final " + normalisedParamTypes.get(j) + " ");

            if (paramNamesForMethod == null) {
                throw new RuntimeException("No name for parameter " + j + " of method " + methodName
                        + " in interface " + this.interfaceTypeRep.getStringRep());
            }
            parameterStrBuilder.append(paramNamesForMethod[j]);

        }
        parameterStrBuilder.append(")");

        final StringBuilder strBuilder = new StringBuilder();
        strBuilder.append(
                "    public " + returnTypeStr + " " + methodName + parameterStrBuilder.toString() + " {\n");
        strBuilder.append("        return null;\n");
        strBuilder.append("    }\n");

        this.methodImplementations.add(strBuilder.toString());

    }

}

From source file:org.brekka.stillingar.spring.bpp.ConfigurationBeanPostProcessor.java

/**
 * Encapsulate a setter method in a {@link ValueDefinition} so that it can be registered for configuration updates.
 * /*from   w  ww.  ja  v  a 2 s  . c  om*/
 * @param configured
 *            the {@link Configured} attribute applied to the method.
 * @param method
 *            the method itself
 * @param valueList
 *            the list of value definitions that the new {@link ValueDefinition} for this field will be added to.
 * @param bean
 *            the bean being configured.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void processSetterMethod(Configured configured, Method method, List<ValueDefinition<?, ?>> valueList,
        Object bean) {
    Class<?>[] parameterTypes = method.getParameterTypes();
    if (parameterTypes.length != 1) {
        throw new ConfigurationException(format("The method '%s' does not appear to be a setter. "
                + "A bean setter method should take only a single parameter.", method));
    }
    Class type = parameterTypes[0];
    boolean list = false;
    ValueDefinition<Object, ?> value;
    if (type == List.class) {
        Type[] genericParameterTypes = method.getGenericParameterTypes();
        type = listType(genericParameterTypes[0]);
        MethodValueChangeListener<List<Object>> listener = new MethodValueChangeListener<List<Object>>(method,
                bean, type, list);
        value = new ValueListDefinition<Object>(type, configured.value(), listener);
    } else {
        MethodValueChangeListener<Object> listener = new MethodValueChangeListener<Object>(method, bean, type,
                list);
        value = new SingleValueDefinition<Object>(type, configured.value(), listener);
    }
    valueList.add(value);
}

From source file:self.philbrown.javaQuery.AjaxOptions.java

/**
 * Used privately by constructors to parse JSON options
 * @param json//from  ww w. j  a  va  2 s  .c  om
 * @throws JSONException
 */
private void handleJSONOptions(JSONObject json) throws JSONException {
    @SuppressWarnings("unchecked")
    Iterator<String> iterator = json.keys();

    while (iterator.hasNext()) {
        String key = iterator.next();
        try {
            Object value = json.get(key);
            for (Method m : methods) {
                if (m.getName().equalsIgnoreCase(key) && m.getGenericParameterTypes().length != 0) {
                    m.invoke(this, value);
                    break;
                }
            }

        } catch (JSONException e) {
            throw new JSONException("Invalid JSON String");
        } catch (Throwable t) {
            if (key != null)
                Log.w("AjaxOptions", "Could not set value " + key);
            else
                throw new NullPointerException("Iterator reference is null.");
        }
    }
}

From source file:dinistiq.Dinistiq.java

/**
 * Injects all available dependencies into a given bean and records all dependencies.
 *
 * @param key key / name/ id of the bean
 * @param bean bean instance/*from  w ww.  jav  a 2s . c  o  m*/
 * @param dependencies dependencies map where the dependecies of the bean are recorded with the given key
 * @throws Exception
 */
private void injectDependencies(Map<String, Set<Object>> dependencies, String key, Object bean)
        throws Exception {
    // Prepare values from properties files
    Properties beanProperties = getProperties(key);
    LOG.debug("injectDependencies({}) bean properties {}", key, beanProperties.keySet());

    // fill injected fields
    Class<? extends Object> beanClass = bean.getClass();
    String beanClassName = beanClass.getName();
    while (beanClass != Object.class) {
        if (bean instanceof Map) {
            fillMap(bean, getProperties(key));
            LOG.info("injectDependencies() filled map '{}' {}", key, bean);
            return; // If it's a map we don't need to inject anything beyond some map properties files.
        } // if
        for (Field field : beanClass.getDeclaredFields()) {
            LOG.debug("injectDependencies({}) field {}", key, field.getName());
            if (field.getAnnotation(Inject.class) != null) {
                Named named = field.getAnnotation(Named.class);
                String name = (named == null) ? null
                        : (StringUtils.isBlank(named.value()) ? field.getName() : named.value());
                LOG.info("injectDependencies({}) {} :{} needs injection with name {}", key, field.getName(),
                        field.getGenericType(), name);
                Object b = getValue(beanProperties, dependencies, key, field.getType(), field.getGenericType(),
                        name);
                final boolean accessible = field.isAccessible();
                try {
                    field.setAccessible(true);
                    field.set(bean, b);
                } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
                    LOG.error("injectDependencies() error setting field " + field.getName() + " :"
                            + field.getType().getName() + " at '" + key + "' :" + beanClassName, e);
                } finally {
                    field.setAccessible(accessible);
                } // try/catch
            } // if
        } // for
        beanClass = beanClass.getSuperclass();
    } // while

    // call methods with annotated injections
    for (Method m : bean.getClass().getMethods()) {
        if (m.getAnnotation(Inject.class) != null) {
            LOG.debug("injectDependencies({}) inject parameters on method {}", key, m.getName());
            Class<? extends Object>[] parameterTypes = m.getParameterTypes();
            Type[] genericParameterTypes = m.getGenericParameterTypes();
            Annotation[][] parameterAnnotations = m.getParameterAnnotations();
            Object[] parameters = getParameters(beanProperties, dependencies, key, parameterTypes,
                    genericParameterTypes, parameterAnnotations);
            try {
                m.invoke(bean, parameters);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                LOG.error("injectDependencies() error injecting for method " + m.getName() + " at '" + key
                        + "' :" + beanClassName, ex);
            } // try/catch
        } // if
    } // for

    // Fill in manually set values from properties file
    for (String property : beanProperties.stringPropertyNames()) {
        String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
        LOG.debug("injectDependencies({}) {} -> {}", key, property, methodName);
        Method m = null;
        // Have to find it just by name
        for (Method me : bean.getClass().getMethods()) {
            if (me.getName().equals(methodName) && (me.getParameterTypes().length > 0)) {
                m = me;
            } // if
        } // for
        if (m == null) {
            LOG.warn("injectDependencies({}) no setter method found for property {}", key, property);
        } else {
            String propertyName = Introspector.decapitalize(m.getName().substring(3));
            Class<?> parameterType = m.getParameterTypes()[0];
            Type genericType = m.getGenericParameterTypes()[0];
            LOG.debug("injectDependencies({}) writable property found {} :{} {}", key, propertyName,
                    parameterType, genericType);
            String propertyValue = beanProperties.getProperty(propertyName); // Must definetely be there without additional check
            boolean isBoolean = (parameterType == Boolean.class) || (m.getParameterTypes()[0] == Boolean.TYPE);
            boolean isCollection = Collection.class.isAssignableFrom(parameterType);
            Object[] parameters = new Object[1];
            LOG.debug("injectDependencies({}) trying to set value {} (bool {}) (collection {}) '{}'", key,
                    propertyName, isBoolean, isCollection, propertyValue);
            try {
                parameters[0] = getReferenceValue(propertyValue);
                if (isBoolean && (parameters[0] instanceof String)) {
                    parameters[0] = Boolean.valueOf(propertyValue);
                } // if
                if ("long".equals(parameterType.getName())) {
                    parameters[0] = new Long(propertyValue);
                } // if
                if ("int".equals(parameterType.getName())) {
                    parameters[0] = new Integer(propertyValue);
                } // if
                if ("float".equals(parameterType.getName())) {
                    parameters[0] = new Float(propertyValue);
                } // if
                if ("double".equals(parameterType.getName())) {
                    parameters[0] = new Double(propertyValue);
                } // if
                if (isCollection) {
                    if (!Collection.class.isAssignableFrom(parameters[0].getClass())) {
                        Collection<Object> values = List.class.isAssignableFrom(parameterType)
                                ? new ArrayList<>()
                                : new HashSet<>();
                        for (String value : propertyValue.split(",")) {
                            values.add(getReferenceValue(value));
                        } // for
                        parameters[0] = values;
                    } // if
                    if (dependencies != null) {
                        for (Object d : (Collection<?>) parameters[0]) {
                            if (beans.containsValue(d)) {
                                dependencies.get(key).add(d);
                            } // if
                        } // if
                    } // if
                } else {
                    if ((dependencies != null) && (beans.containsValue(parameters[0]))) {
                        dependencies.get(key).add(parameters[0]);
                    } // if
                } // if
                LOG.debug("injectDependencies({}) setting value {} '{}' :{}", key, propertyName, parameters[0],
                        parameters[0].getClass());
                m.invoke(bean, parameters);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                LOG.error("injectDependencies() error setting property " + propertyName + " to '"
                        + propertyValue + "' at " + key + " :" + beanClassName, ex);
            } // try/catch
        } // if
    } // for
}

From source file:com.github.helenusdriver.driver.tools.Tool.java

/**
 * Finds an initial objects factory method and its dependent classes from the
 * specified object creator class./* w  w  w  .  j  a v a  2  s .c  o m*/
 *
 * @author paouelle
 *
 * @param  clazz the non-<code>null</code> object creator class
 * @return the initial objects factory method and its set of dependenc classes
 *         or <code>null</code> if none configured
 * @throws IllegalArgumentException if the initial objects method is not
 *         properly defined
 */
private static Pair<Method, Class<?>[]> findInitial(Class<?> clazz) {
    final InitialObjects io = clazz.getAnnotation(InitialObjects.class);

    if (io != null) {
        final String mname = io.staticMethod();

        try {
            Method m;

            try { // first look for one with a map for suffixes
                m = clazz.getMethod(mname, Map.class);
                // validate that if suffixes are defined, the method expects a Map<String, String>
                // to provide the values for the suffixes when initializing objects
                final Class<?>[] cparms = m.getParameterTypes();

                // should always be 1 as we used only 1 class in getMethod()
                if (cparms.length != 1) {
                    throw new IllegalArgumentException(
                            "expecting one Map<String, String> parameter for initial objects method '" + mname
                                    + "' in class: " + clazz.getSimpleName());
                }
                // should always be a map as we used a Map to find the method
                if (!Map.class.isAssignableFrom(cparms[0])) {
                    throw new IllegalArgumentException("expecting parameter for initial objects method '"
                            + mname + "' to be of type Map<String, String> in class: " + clazz.getSimpleName());
                }
                final Type[] tparms = m.getGenericParameterTypes();

                // should always be 1 as we used only 1 class in getMethod()
                if (tparms.length != 1) { // should always be 1 as it was already tested above
                    throw new IllegalArgumentException(
                            "expecting one Map<String, String> parameter for initial objects method '" + mname
                                    + "' in class: " + clazz.getSimpleName());
                }
                if (tparms[0] instanceof ParameterizedType) {
                    final ParameterizedType ptype = (ParameterizedType) tparms[0];

                    // maps will always have 2 arguments
                    for (final Type atype : ptype.getActualTypeArguments()) {
                        final Class<?> aclazz = ReflectionUtils.getRawClass(atype);

                        if (String.class != aclazz) {
                            throw new IllegalArgumentException(
                                    "expecting a Map<String, String> parameter for initial objects method '"
                                            + mname + "' in class: " + clazz.getSimpleName());
                        }
                    }
                } else {
                    throw new IllegalArgumentException(
                            "expecting a Map<String, String> parameter for initial objects method '" + mname
                                    + "' in class: " + clazz.getSimpleName());
                }
            } catch (NoSuchMethodException e) { // fallback to one with no map
                m = clazz.getMethod(mname);
            }
            // validate the method is static
            if (!Modifier.isStatic(m.getModifiers())) {
                throw new IllegalArgumentException("initial objects method '" + mname
                        + "' is not static in class: " + clazz.getSimpleName());
            }
            // validate the return type is an array
            final Class<?> type = m.getReturnType();

            if (!type.isArray()) {
                throw new IllegalArgumentException("initial objects method '" + mname
                        + "' doesn't return an array in class: " + clazz.getSimpleName());
            }
            return Pair.of(m, io.dependsOn());
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException(
                    "missing initial objects method '" + mname + "' in class: " + clazz.getSimpleName(), e);
        }
    }
    return null;
}

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

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

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

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

    if (!Properties.USE_DEPRECATED && m.isAnnotationPresent(Deprecated.class)) {
        final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();

        if (Properties.hasTargetClassBeenLoaded() && !m.getDeclaringClass().equals(targetClass)) {
            logger.debug("Excluding deprecated method " + m.getName());
            return false;
        }
    }

    if (m.isAnnotationPresent(Test.class) || m.isAnnotationPresent(Before.class)
            || m.isAnnotationPresent(BeforeClass.class) || m.isAnnotationPresent(After.class)
            || m.isAnnotationPresent(AfterClass.class)) {
        logger.debug("Excluding test method " + m.getName());
        return false;
    }

    if (m.isAnnotationPresent(EvoSuiteTest.class)) {
        logger.debug("Excluding EvoSuite 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()) || !canUse(m.getGenericReturnType()))) {
        return false;
    }

    for (java.lang.reflect.Type paramType : m.getGenericParameterTypes()) {
        if (!canUse(paramType))
            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")) {
        final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();

        if (!m.getDeclaringClass().equals(targetClass))
            return false;
        else {
            if (GraphPool.getInstance(ownerClass.getClassLoader()).getActualCFG(Properties.TARGET_CLASS,
                    m.getName() + Type.getMethodDescriptor(m)) == null) {
                // Don't cover generated hashCode
                // TODO: This should work via annotations
                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 method");
        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())) {
        TestClusterUtils.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)) {
            TestClusterUtils.makeAccessible(m);
            return true;
        }
    }

    return false;
}