Example usage for java.lang.reflect Method getName

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

Introduction

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

Prototype

@Override
public String getName() 

Source Link

Document

Returns the name of the method represented by this Method object, as a String .

Usage

From source file:com.google.code.siren4j.util.ReflectionUtils.java

/**
 * Find the field for the getter method based on the get methods name. It finds the field on the declaring class.
 *
 * @param method cannot be <code>null</code>.
 * @return the field or <code>null</code> if not found.
 *//* www.j  av a  2  s.  com*/
public static Field getGetterField(Method method) {
    if (method == null) {
        throw new IllegalArgumentException("method cannot be null.");
    }
    Class<?> clazz = method.getDeclaringClass();
    String fName = stripGetterPrefix(method.getName());
    Field field = null;
    try {
        field = findField(clazz, fName);
    } catch (Exception ignore) {
    }
    return field;

}

From source file:edu.ku.brc.af.ui.forms.FormHelper.java

public static void dumpDataObj(final DataProviderSessionIFace session, final Object dataObj,
        final Hashtable<Class<?>, Boolean> clsHash, final int level) {
    if (dataObj == null || clsHash.get(dataObj.getClass()) != null)
        return;//from   w  w w  .  java 2 s  .  c om

    String clsName = dataObj.getClass().toString();
    if (clsName.indexOf("CGLIB") > -1)
        return;

    StringBuilder indent = new StringBuilder();
    for (int i = 0; i < level; i++)
        indent.append("  ");

    for (Method method : dataObj.getClass().getMethods()) {
        String methodName = method.getName();
        if (!methodName.startsWith("get") || method.getModifiers() == 9) {
            continue;
        }

        String fieldName = methodName.substring(3, 4).toLowerCase()
                + methodName.substring(4, methodName.length());
        Object kidData = null;
        try {
            kidData = getValue((FormDataObjIFace) dataObj, fieldName);

        } catch (Exception ex) {
            System.out.println(indent + fieldName + " = <no data>");
        }
        if (kidData != null) {
            if (kidData instanceof Set<?>) {
                for (Object obj : ((Set<?>) kidData)) {
                    System.out.println(indent + fieldName + " = " + obj);
                    if (obj instanceof FormDataObjIFace) {
                        dumpDataObj(session, obj, clsHash, level + 1);
                    }
                }
            } else {
                System.out.println(indent + fieldName + " = " + kidData);
                if (kidData instanceof FormDataObjIFace) {
                    session.attach(kidData);
                    dumpDataObj(session, kidData, clsHash, level + 1);
                }
            }

        }

    }
}

From source file:de.codesourcery.eve.apiclient.parsers.HttpAPIClientTest.java

private static Method findParserMethod(String name, Class<?>... args) throws Exception {
    try {/*from www. j a va  2s .c  o m*/
        return AbstractResponseParser.class.getDeclaredMethod(name, args);
    } catch (Exception e) {
        try {
            return AbstractResponseParser.class.getMethod(name, args);
        } catch (Exception e2) {

            for (Method m : AbstractResponseParser.class.getMethods()) {

                if (!m.getName().equals(name)) {
                    System.out.println("# Name mismatch: " + m);
                    continue;
                }

                if (!ObjectUtils.equals(m.getParameterTypes(), args)) {
                    System.out.println("# Param mismatch: " + m);
                    continue;
                }

                final int modifiers = m.getModifiers();

                if (Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers)
                        || Modifier.isFinal(modifiers)) {
                    System.out.println("# Modifier mismatch: " + m);
                    continue;
                }

                return m;
            }
            throw e2;
        }
    }
}

From source file:io.swagger.jaxrs.MethodProcessor.java

static Operation parseMethod(Class<?> cls, Method method, List<Parameter> globalParameters, Swagger swagger) {
    Operation operation = new Operation();

    ApiOperation apiOperationAnnotation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
    ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class);

    String operationId = method.getName();
    String responseContainer = null;

    Type responseType = null;/*from   ww  w  .  j  a  v  a 2s .c  om*/
    Map<String, Property> defaultResponseHeaders = new HashMap<>();

    if (apiOperationAnnotation != null) {
        if (apiOperationAnnotation.hidden()) {
            return null;
        }
        if (!"".equals(apiOperationAnnotation.nickname())) {
            operationId = apiOperationAnnotation.nickname();
        }

        defaultResponseHeaders = parseResponseHeaders(swagger, apiOperationAnnotation.responseHeaders());

        operation.summary(apiOperationAnnotation.value()).description(apiOperationAnnotation.notes());

        if (apiOperationAnnotation.response() != null && !isVoid(apiOperationAnnotation.response())) {
            responseType = apiOperationAnnotation.response();
        }
        if (!"".equals(apiOperationAnnotation.responseContainer())) {
            responseContainer = apiOperationAnnotation.responseContainer();
        }
        if (apiOperationAnnotation.authorizations() != null) {
            List<SecurityRequirement> securities = new ArrayList<>();
            for (Authorization auth : apiOperationAnnotation.authorizations()) {
                if (auth.value() != null && !"".equals(auth.value())) {
                    SecurityRequirement security = new SecurityRequirement();
                    security.setName(auth.value());
                    AuthorizationScope[] scopes = auth.scopes();
                    for (AuthorizationScope scope : scopes) {
                        if (scope.scope() != null && !"".equals(scope.scope())) {
                            security.addScope(scope.scope());
                        }
                    }
                    securities.add(security);
                }
            }
            if (securities.size() > 0) {
                securities.stream().forEach((sec) -> {
                    operation.security(sec);
                });
            }
        }
        if (apiOperationAnnotation.consumes() != null && !apiOperationAnnotation.consumes().isEmpty()) {
            operation.consumes(apiOperationAnnotation.consumes());
        }
        if (apiOperationAnnotation.produces() != null && !apiOperationAnnotation.produces().isEmpty()) {
            operation.produces(apiOperationAnnotation.produces());
        }
    }

    if (apiOperationAnnotation != null && StringUtils.isNotEmpty(apiOperationAnnotation.responseReference())) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);
        response.schema(new RefProperty(apiOperationAnnotation.responseReference()));
        operation.addResponse(String.valueOf(apiOperationAnnotation.code()), response);
    } else if (responseType == null) {
        // pick out response from method declaration
        //handle Response types
        if (method.getGenericReturnType() instanceof ParameterizedType
                && org.thingsplode.synapse.core.Response.class.isAssignableFrom(
                        (Class<?>) ((ParameterizedType) method.getGenericReturnType()).getRawType())) {
            responseType = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0];
        } else {
            responseType = method.getGenericReturnType();
        }

    }
    if (isValidResponse(responseType)) {
        final Property property = ModelConverters.getInstance().readAsProperty(responseType);
        if (property != null) {
            final Property responseProperty = Reader.ContainerWrapper.wrapContainer(responseContainer,
                    property);
            final int responseCode = apiOperationAnnotation == null ? 200 : apiOperationAnnotation.code();
            operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION)
                    .schema(responseProperty).headers(defaultResponseHeaders));
            appendModels(swagger, responseType);
        }
    }

    operation.operationId(operationId);

    if (apiOperationAnnotation != null && apiOperationAnnotation.consumes() != null
            && apiOperationAnnotation.consumes().isEmpty()) {
        //todo: check what to do with consumers
        //            final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class);
        //            if (consumes != null) {
        //                for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) {
        //                    operation.consumes(mediaType);
        //                }
        //            }
    }

    if (apiOperationAnnotation != null && apiOperationAnnotation.produces() != null
            && apiOperationAnnotation.produces().isEmpty()) {
        //todo: check what to do with produces
        //            final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class);
        //            if (produces != null) {
        //                for (String mediaType : ReaderUtils.splitContentValues(produces.value())) {
        //                    operation.produces(mediaType);
        //                }
        //            }
    }

    List<ApiResponse> apiResponses = new ArrayList<>();
    if (responseAnnotation != null) {
        apiResponses.addAll(Arrays.asList(responseAnnotation.value()));
    }

    Class<?>[] exceptionTypes = method.getExceptionTypes();
    for (Class<?> exceptionType : exceptionTypes) {
        ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class);
        if (exceptionResponses != null) {
            apiResponses.addAll(Arrays.asList(exceptionResponses.value()));
        }
    }

    for (ApiResponse apiResponse : apiResponses) {
        Map<String, Property> responseHeaders = parseResponseHeaders(swagger, apiResponse.responseHeaders());

        Response response = new Response().description(apiResponse.message()).headers(responseHeaders);

        if (apiResponse.code() == 0) {
            operation.defaultResponse(response);
        } else {
            operation.response(apiResponse.code(), response);
        }

        if (StringUtils.isNotEmpty(apiResponse.reference())) {
            response.schema(new RefProperty(apiResponse.reference()));
        } else if (!isVoid(apiResponse.response())) {
            responseType = apiResponse.response();
            final Property property = ModelConverters.getInstance().readAsProperty(responseType);
            if (property != null) {
                response.schema(
                        Reader.ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
                appendModels(swagger, responseType);
            }
        }
    }
    if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) {
        operation.setDeprecated(true);
    }

    // process parameters
    //=====================
    globalParameters.stream().forEach((globalParameter) -> {
        operation.parameter(globalParameter);
    });

    ParameterExtractor.getParameters(swagger, cls, method).forEach(p -> operation.parameter(p));

    if (operation.getResponses() == null) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);
        operation.defaultResponse(response);
    }
    return operation;
}

From source file:gov.nih.nci.caarray.util.CaArrayUtils.java

/**
 * For given class, returns a ReflectionHelper instance with property accessors for the class.
 * /*from  ww  w.j  av a  2  s  .co m*/
 * @param clazz the class
 * @return the ReflectionHelper
 */
public static ReflectionHelper createReflectionHelper(Class<?> clazz) {
    final List<PropertyAccessor> accessors = new ArrayList<PropertyAccessor>();

    Class<?> currentClass = clazz;
    while (currentClass != null) {
        final Method[] methods = currentClass.getDeclaredMethods();
        for (final Method getter : methods) {
            if (getter.getName().startsWith("get") && getter.getParameterTypes().length == 0) {
                for (final Method setter : methods) {
                    if (setter.getName().equals('s' + getter.getName().substring(1))
                            && setter.getParameterTypes().length == 1
                            && Void.TYPE.equals(setter.getReturnType())
                            && getter.getReturnType().equals(setter.getParameterTypes()[0])) {
                        getter.setAccessible(true);
                        setter.setAccessible(true);
                        accessors.add(new PropertyAccessor(getter, setter));
                    }
                }
            }
        }

        currentClass = currentClass.getSuperclass();
    }

    return new ReflectionHelper(accessors.toArray(new PropertyAccessor[accessors.size()]));
}

From source file:eu.crisis_economics.abm.model.ModelUtils.java

/**
  * A depth first recursive parameter search tool. This function accepts an object
  * {@code X}, the ({@link String}) name {@code N} of a method, and a {@link Class} array
  * of method argument types. Any object in the configuration hierarchy of {@code X} which
  * has a method with with the appropriate signature and arguments is found and
  * returned.<br>//  w ww .ja  va 2 s  .  co m
  * 
  * This search operates as follows:
  * 
  * <ul>
  *   <li> If {@code X} contains a method {@code N} with the specified arguments, then 
  *        store and remember this method;
  *   <li> Otherwise search the subclasses of {@code X} for a method {@code N} with
  *        the specified arguments. If such a method is found, then store and
  *        remember this method;
  *   <li> Apply the above steps recursively (depth first) to every field in {@code X}
  *        of type {@link ComponentConfiguration}. Remember all of the methods identified
  *        by this search process and return these methods as well as the object 
  *        instances in which they were found.
  * </ul>
  * 
  * @param on
  *        The object to search.
  * @param methodToFind
  *        The method name to search for.
  * @param arguments
  *        A list of {@link Class} argument types for the method to find.
  * @return
  *        A {@link List} of {@link Pair}{@code s}. Each entry in this list is a {@link Pair}
  *        composed of one {@link Method} object and one {@link Object}. The {@link Method}
  *        satisfies the parameters of the query. The {@link Object} is an instance of an
  *        object whose class possesses the {@link Method}.
  */
public static List<Pair<Method, Object>> search(final Object on, final String methodToFind,
        final Class<?>[] arguments) {
    final List<Pair<Method, Object>> result = new ArrayList<Pair<Method, Object>>();
    final Class<?> parentType = on.getClass();
    for (Class<?> typeToSearch = parentType; typeToSearch != null; typeToSearch = typeToSearch
            .getSuperclass()) {
        Method methodPtr = null;
        try {
            // Try to find a method with the specified name and exact argument types:
            methodPtr = typeToSearch.getDeclaredMethod(methodToFind, arguments);
            result.add(Pair.create(methodPtr, on));
            continue;
        } catch (final NoSuchMethodException e) {
            // Try to downcast method arguments for other class methods with the correct name:
            final Method[] allCalleeMethods = typeToSearch.getDeclaredMethods();
            for (final Method method : allCalleeMethods) {
                if (!method.getName().equals(methodToFind))
                    continue;
                final Type[] argTypes = method.getGenericParameterTypes();
                if (argTypes.length != arguments.length)
                    continue;
                for (int j = 0; j < arguments.length; ++j) {
                    if (!arguments[j].isAssignableFrom(argTypes[j].getClass()))
                        continue;
                }
                methodPtr = method;
                result.add(Pair.create(methodPtr, on));
                continue;
            }
        }
        if (methodPtr == null)
            continue;
    }
    // Search for any ComponentConfiguration fields in the specified object:
    for (Class<?> typeToSearch = parentType; typeToSearch != null; typeToSearch = typeToSearch
            .getSuperclass()) {
        for (Field field : typeToSearch.getDeclaredFields()) {
            if (!ComponentConfiguration.class.isAssignableFrom(field.getType()))
                continue;
            field.setAccessible(true);
            final Object instance;
            try {
                instance = field.get(on);
            } catch (final IllegalArgumentException e) {
                continue; // Not found
            } catch (final IllegalAccessException e) {
                continue; // Not found
            }
            if (instance != null) {
                final List<Pair<Method, Object>> subResult = search(instance, methodToFind, arguments); // Descend into fields
                if (subResult != null && !subResult.isEmpty())
                    result.addAll(subResult);
                else
                    continue;
            }
        }
    }
    return result;
}

From source file:dk.netdesign.common.osgi.config.Attribute.java

private static Class getMethodReturnType(Method classMethod) throws InvalidMethodException {
    Class methodReturnType = classMethod.getReturnType();
    if (classMethod.isAnnotationPresent(Property.class)) {
        Property methodProperty = classMethod.getAnnotation(Property.class);
        if (List.class.isAssignableFrom(methodReturnType) && methodProperty.type() == void.class) {
            throw new InvalidMethodException("Could not create handler for method " + classMethod.getName()
                    + ". Lists must be accompanied by a returnType");
        }/*  w  ww .  j  a  v a 2 s  .  co  m*/
    }
    return methodReturnType;
}

From source file:eu.crisis_economics.abm.model.ModelUtils.java

public static List<GetterSetterPair> parameters(final Object of, final Class<?> paramType) {
    final List<GetterSetterPair> result = new ArrayList<GetterSetterPair>();
    final Class<?> parentType = of.getClass();
    for (Class<?> typeToSearch = parentType; typeToSearch != null; typeToSearch = typeToSearch
            .getSuperclass()) {/*from  w w w. j av  a 2 s.  c  o  m*/
        final Map<String, Method> methodNames = new HashMap<String, Method>();
        final Method[] allCalleeMethods = typeToSearch.getDeclaredMethods();
        for (final Method method : allCalleeMethods) {
            final String name = method.getName();
            if (name.startsWith("get") && ClassUtils.isAssignable(paramType, method.getReturnType(), true))
                methodNames.put(method.getName(), method);
            else if (name.startsWith("set") && method.getParameterTypes().length == 1
                    && ClassUtils.isAssignable(paramType, method.getParameterTypes()[0], true))
                methodNames.put(method.getName(), method);
            else
                continue;
            final String complement;
            if (name.startsWith("get")) {
                complement = "set" + name.substring(3);
                if (methodNames.containsKey(complement))
                    result.add(new GetterSetterPair(method, methodNames.get(complement), of));
            } else if (name.startsWith("set")) {
                complement = "get" + name.substring(3);
                if (methodNames.containsKey(complement))
                    result.add(new GetterSetterPair(methodNames.get(complement), method, of));
            }
        }
    }
    // Search for any ComponentConfiguration fields in the specified object:
    for (Class<?> typeToSearch = parentType; typeToSearch != null; typeToSearch = typeToSearch
            .getSuperclass()) {
        for (Field field : typeToSearch.getDeclaredFields()) {
            if (!ComponentConfiguration.class.isAssignableFrom(field.getType()))
                continue;
            field.setAccessible(true);
            final Object instance;
            try {
                instance = field.get(of);
            } catch (final IllegalArgumentException e) {
                continue; // Not found
            } catch (final IllegalAccessException e) {
                continue; // Not found
            }
            if (instance != null) {
                final List<GetterSetterPair> subResult = parameters(instance, paramType); // Descend into fields
                if (subResult != null && !subResult.isEmpty())
                    result.addAll(subResult);
                else
                    continue;
            }
        }
    }
    return result;
}

From source file:com.haulmont.cuba.core.config.ConfigUtil.java

/**
 * Search for an annotation on a configuration interface method. In
 * addition to searching the method itself, the {@link #getGetMethod
 * plain get method} is also searched, as can the {@link
 * #getMethodType method type} be./*  w w  w.  j  a  v  a  2  s .  c  o m*/
 *
 * @param configInterface  The configuration interface.
 * @param method           The method.
 * @param annotationType   The annotation type of interest.
 * @param searchMethodType Whether to search the method type.
 * @return The annotation, or null.
 */
public static <T extends Annotation> T getAnnotation(Class<?> configInterface, Method method,
        Class<T> annotationType, boolean searchMethodType) {
    T annotation = method.getAnnotation(annotationType);
    if (annotation == null) {
        Method getMethod = getGetMethod(configInterface, method);
        if (getMethod != null) {
            annotation = getMethod.getAnnotation(annotationType);
        }
        if ((annotation == null) && searchMethodType) {
            String methodName = method.getName();
            if (ACCESS_RE.matcher(methodName).matches()) {
                // Is the annotation present on the method type?
                Class<?> methodType = getMethodType(method);
                annotation = methodType.getAnnotation(annotationType);
            }
        }
    }
    return annotation;
}

From source file:com.tugo.dt.PojoUtils.java

private static String getSingleFieldSetterExpression(final Class<?> pojoClass, final String fieldExpression,
        final Class<?> exprClass) {
    JavaStatement code = new JavaStatement(
            pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32);
    /* Construct ((<pojo class name>)pojo). */
    code.appendCastToTypeExpr(pojoClass, OBJECT).append(".");
    try {// www.ja  va2  s.com
        final Field field = pojoClass.getField(fieldExpression);
        if (ClassUtils.isAssignable(exprClass, field.getType())) {
            /* there is public field on the class, use direct assignment. */
            /* append <field name> = (<field type>)val; */
            return code.append(field.getName()).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        }
        logger.debug("{} can not be assigned to {}. Proceeding to locate a setter method.", exprClass, field);
    } catch (NoSuchFieldException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    }

    final String setMethodName = SET + upperCaseWord(fieldExpression);
    Method bestMatchMethod = null;
    List<Method> candidates = new ArrayList<Method>();
    for (Method method : pojoClass.getMethods()) {
        if (setMethodName.equals(method.getName())) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                if (exprClass == parameterTypes[0]) {
                    bestMatchMethod = method;
                    break;
                } else if (org.apache.commons.lang.ClassUtils.isAssignable(exprClass, parameterTypes[0])) {
                    candidates.add(method);
                }
            }
        }
    }

    if (bestMatchMethod == null) { // We did not find the exact match, use candidates to find the match
        if (candidates.size() == 0) {
            logger.debug("{} does not have suitable setter method {}. Returning original expression {}.",
                    pojoClass, setMethodName, fieldExpression);
            /* We did not find any match at all, use original expression */
            /* append = (<expr type>)val;*/
            return code.append(fieldExpression).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        } else {
            // TODO: see if we can find a better match
            bestMatchMethod = candidates.get(0);
        }
    }

    /* We found a method that we may use for setter */
    /* append <method name>((<expr class)val); */
    return code.append(bestMatchMethod.getName()).append("(").appendCastToTypeExpr(exprClass, VAL).append(")")
            .getStatement();
}