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:Main.java

/**
 * Given a method, which may come from an interface, and a target class used in the current reflective invocation, find the corresponding target method if there is one. E.g. the method may be <code>IFoo.bar()</code> and the target class may be <code>DefaultFoo</code>. In this case, the method may be <code>DefaultFoo.bar()</code>. This enables attributes on that method to be found.
 * <p>/*from  www.j av a2  s .c  o m*/
 * <b>NOTE:</b> In contrast to {@link org.springframework.aop.support.AopUtils#getMostSpecificMethod}, this method does <i>not</i> resolve Java 5 bridge methods automatically. Call {@link org.springframework.core.BridgeMethodResolver#findBridgedMethod} if bridge method resolution is desirable (e.g. for obtaining metadata from the original method definition).
 * 
 * @param method
 *          the method to be invoked, which may come from an interface
 * @param targetClass
 *          the target class for the current invocation. May be <code>null</code> or may not even implement the method.
 * @return the specific target method, or the original method if the <code>targetClass</code> doesn't implement it or is <code>null</code>
 * @see org.springframework.aop.support.AopUtils#getMostSpecificMethod
 */
public static Method getMostSpecificMethod(Method method, Class<?> targetClass) {
    if (method != null && targetClass != null) {
        try {
            method = targetClass.getMethod(method.getName(), method.getParameterTypes());
        } catch (NoSuchMethodException ex) {
            // Perhaps the target class doesn't implement this method:
            // that's fine, just use the original method.
        }
    }
    return method;
}

From source file:ReflectionTest.java

/**
 * Prints all methods of a class//from   w w w.ja  v a2 s  .  c o  m
 * @param cl a class
 */
public static void printMethods(Class cl) {
    Method[] methods = cl.getDeclaredMethods();

    for (Method m : methods) {
        Class retType = m.getReturnType();
        String name = m.getName();

        System.out.print("   ");
        // print modifiers, return type and method name
        String modifiers = Modifier.toString(m.getModifiers());
        if (modifiers.length() > 0)
            System.out.print(modifiers + " ");
        System.out.print(retType.getName() + " " + name + "(");

        // print parameter types
        Class[] paramTypes = m.getParameterTypes();
        for (int j = 0; j < paramTypes.length; j++) {
            if (j > 0)
                System.out.print(", ");
            System.out.print(paramTypes[j].getName());
        }
        System.out.println(");");
    }
}

From source file:Main.java

/**
 * search the method and return the defined method.
 * it will {@link Class#getMethod(String, Class[])}, if exception occurs,
 * it will search for all methods, and find the most fit method.
 *//*w  w  w  .j  av  a  2s  . co m*/
public static Method searchMethod(Class<?> currentClass, String name, Class<?>[] parameterTypes, boolean boxed)
        throws NoSuchMethodException {
    if (currentClass == null) {
        throw new NoSuchMethodException("class == null");
    }
    try {
        return currentClass.getMethod(name, parameterTypes);
    } catch (NoSuchMethodException e) {
        Method likeMethod = null;
        for (Method method : currentClass.getMethods()) {
            if (method.getName().equals(name) && parameterTypes.length == method.getParameterTypes().length
                    && Modifier.isPublic(method.getModifiers())) {
                if (parameterTypes.length > 0) {
                    Class<?>[] types = method.getParameterTypes();
                    boolean eq = true;
                    boolean like = true;
                    for (int i = 0; i < parameterTypes.length; i++) {
                        Class<?> type = types[i];
                        Class<?> parameterType = parameterTypes[i];
                        if (type != null && parameterType != null && !type.equals(parameterType)) {
                            eq = false;
                            if (boxed) {
                                type = getBoxedClass(type);
                                parameterType = getBoxedClass(parameterType);
                            }
                            if (!type.isAssignableFrom(parameterType)) {
                                eq = false;
                                like = false;
                                break;
                            }
                        }
                    }
                    if (!eq) {
                        if (like && (likeMethod == null || likeMethod.getParameterTypes()[0]
                                .isAssignableFrom(method.getParameterTypes()[0]))) {
                            likeMethod = method;
                        }
                        continue;
                    }
                }
                return method;
            }
        }
        if (likeMethod != null) {
            return likeMethod;
        }
        throw e;
    }
}

From source file:com.jaspersoft.jasperserver.util.QueryUtil.java

/**
 * Execute DataBaseMetaData methods using reflection
 * @param dmd//from w w w. j  a v a2s . co  m
 * @param methodName
 * @param parameters
 * @return
 * @throws ClassNotFoundException
 */
public static Method findMethod(DatabaseMetaData dmd, String methodName, Object[] parameters)
        throws ClassNotFoundException {
    long startTime = System.currentTimeMillis();
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Enter findMethod .. Start Time" + System.currentTimeMillis());
        }
        Class cl = Class.forName("java.sql.DatabaseMetaData");
        Method[] methods = cl.getDeclaredMethods();
        // Trying to avoid collision of methods with varying parameters and avoid having to do parameter class types

        int paramCount = 0;
        if (null != parameters) {
            paramCount = parameters.length;
        }

        for (Method m : methods) {
            if (m.getName().equals(methodName)) {
                if (Modifier.isPublic(m.getModifiers()) && m.getParameterTypes().length == paramCount) {
                    return m;
                }
            }
        } //for
        return null;
    } finally {
        if (logger.isDebugEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.debug("Exit findMethod .. Total Time Spent: " + elapsedTime);
        }
    }

}

From source file:api.Status.java

public static Result getStatus() {
    ObjectNode metrics = Json.newObject();

    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    TreeMap<String, Object> values = new TreeMap<String, Object>();
    for (Method method : os.getClass().getDeclaredMethods()) {
        method.setAccessible(true);/*from  w w  w .  j a v  a2s .  c  o m*/
        if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) {
            Object value;
            try {
                value = method.invoke(os);
                values.put(method.getName(), value);
            } catch (Exception e) {
                Logger.warn("Error when invoking " + os.getClass().getName()
                        + " (OperatingSystemMXBean) method " + method.getName() + ": " + e);
            } // try
        } // if
    } // for

    metrics.put("jvmLoad", (Double) values.get("getProcessCpuLoad"));
    metrics.put("cpuLoad", (Double) values.get("getSystemCpuLoad"));
    metrics.put("openFD", (Long) values.get("getOpenFileDescriptorCount"));
    metrics.put("maxFD", (Long) values.get("getMaxFileDescriptorCount"));
    metrics.put("freeMemory", (Long) values.get("getFreePhysicalMemorySize"));
    metrics.put("totalMemory", (Long) values.get("getTotalPhysicalMemorySize"));

    return ok(metrics.toString());
}

From source file:com.iorga.iraj.json.MethodTemplate.java

private static String getPropertyNameFromMethod(final Method targetMethod) {
    String name = targetMethod.getName();
    if (name.startsWith("get")) {
        name = name.substring(3);//  ww  w  .j a v  a2s  . c om
    } else if (name.startsWith("is")) {
        name = name.substring(2);
    }
    return StringUtils.uncapitalize(name);
}

From source file:com.ngdata.sep.util.io.Closer.java

public static void close(Object object) {
    if (object != null) {
        try {/*  www .  jav  a2  s.c om*/
            Method closeMethod = null;
            Method[] methods = object.getClass().getMethods();
            for (Method method : methods) {
                if (method.getParameterTypes().length == 0) {
                    if (method.getName().equals("close")) {
                        closeMethod = method;
                        break;
                    } else if (method.getName().equals("shutdown")) {
                        closeMethod = method;
                    } else if (method.getName().equals("stop")) {
                        closeMethod = method;
                    }
                }
            }

            if (closeMethod != null) {
                closeMethod.invoke(object);
            } else {
                Log log = LogFactory.getLog(Closer.class);
                log.error("Do not know how to close object of type " + object.getClass().getName());
            }
        } catch (Throwable t) {
            Log log = LogFactory.getLog(Closer.class);
            log.error("Error closing object of type " + object.getClass().getName(), t);
        }
    }
}

From source file:com.weibo.api.motan.protocol.grpc.GrpcUtil.java

public static Method getMethod(String name, Class<?> interfaceClazz) {
    int index = name.lastIndexOf("/");
    if (index > -1) {
        name = name.substring(name.lastIndexOf("/") + 1);
    }/* w ww.j av a 2  s .co m*/

    Method[] methods = interfaceClazz.getMethods();
    for (Method m : methods) {
        if (m.getName().equalsIgnoreCase(name)) {
            return m;
        }
    }
    throw new MotanFrameworkException("not find grpc method");
}

From source file:com.sonatype.security.ldap.api.DeepEqualsBuilder.java

private static boolean classHasEqualsMethod(Class clazz) {
    if (clazz != null) {
        Method[] methods = clazz.getDeclaredMethods();
        for (int ii = 0; ii < methods.length; ii++) {
            Method method = methods[ii];
            if ("equals".equals(method.getName()) && method.getParameterTypes().length == 1
                    && method.getParameterTypes()[0].equals(Object.class)) {
                return true;
            }/*from   w  ww  . j  a  v  a 2s  . c  o  m*/
        }
    }
    return false;
}

From source file:com.hubrick.vertx.rest.converter.JacksonJsonHttpMessageConverter.java

private static Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>... paramTypes) {
    checkNotNull(clazz, "Class must not be null");
    checkNotNull(methodName, "Method name must not be null");
    if (paramTypes != null) {
        try {/*from   w w  w.j ava2  s.  c om*/
            return clazz.getMethod(methodName, paramTypes);
        } catch (NoSuchMethodException ex) {
            return null;
        }
    } else {
        Set<Method> candidates = new HashSet<>(1);
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                candidates.add(method);
            }
        }
        if (candidates.size() == 1) {
            return candidates.iterator().next();
        }
        return null;
    }
}